josiftepe

Untitled

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