josiftepe

Untitled

Jan 19th, 2021
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.09 KB | None | 0 0
  1. public class Main {
  2.  
  3.     public static void main(String[] args) {
  4.         Node list1 = new Node();
  5.         list1.insert_node_at_end(10);
  6.         list1.insert_node_at_end(20);
  7.         list1.insert_node_at_end(30);
  8.         list1.insert_node_at_end(40);
  9.         list1.print();
  10.         Node list2 = new Node();
  11.         list2 = reverse_list(list1);
  12.         list2.print();
  13.  
  14.  
  15.     }
  16.     public static Node reverse_list(Node list) {
  17.         Node ret = new Node();
  18.         Node tmp = list.head;
  19.         while(tmp != null) {
  20.             ret.insert_node_at_beginning(tmp.info);
  21.             tmp = tmp.next;
  22.         }
  23.         return ret;
  24.     }
  25. }
  26.  
  27. class Node {
  28.     Node head; // first node in the List
  29.     Node next;
  30.     int info; // storing bunch of integers
  31.     Node() {
  32.         head = null;
  33.         next = null;
  34.     }
  35.     Node(int x) {
  36.         info = x;
  37.         next = null;
  38.     }
  39.     public void insert_node_at_beginning(int x) { // data which the new node will store
  40.         if(head == null) { // empty linked list
  41.             head = new Node(x);
  42.             return;
  43.         }
  44.         Node new_node = new Node(x);
  45.         new_node.next = head;
  46.         head = new_node;
  47.     }
  48.     public void insert_node_at_end(int x) { // at the end insert a node
  49.         Node new_node = new Node(x);
  50.         if(head == null) {
  51.             head = new Node(x);
  52.             return;
  53.         }
  54.         Node tmp = head;
  55.         while(tmp.next != null) {
  56.             tmp = tmp.next;
  57.         }
  58.         tmp.next = new_node;
  59.         new_node.next = null;
  60.     }
  61.     public void delete_node(int x) { // data which should get deleted
  62.         Node tmp = head;
  63.         Node prev = null; // previous node
  64.         while(tmp.info != x) { // iterate through the list till the node which should get deleted
  65.             prev = tmp;
  66.             tmp = tmp.next;
  67.         }
  68.         prev.next = tmp.next;
  69.     }
  70.     public void print() {
  71.         Node tmp = head;
  72.         while(tmp != null) {
  73.             System.out.print(tmp.info + "-> ");
  74.             tmp = tmp.next;
  75.         }
  76.         System.out.println();
  77.     }
  78.  
  79. }
  80.  
Advertisement
Add Comment
Please, Sign In to add comment