Advertisement
Josif_tepe

Untitled

Nov 4th, 2021
150
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.59 KB | None | 0 0
  1. public class Algoritmi {
  2.     public static void main(String[] args) {
  3.         LinkedList list = new LinkedList();
  4.       list.insert_node_at_end(1);
  5.         list.insert_node_at_end(2);
  6.         list.insert_node_at_end(3);
  7.  
  8.         list.print();
  9.         list.delete_node(2);
  10.         list.print();
  11.     }
  12. }
  13. class LinkedList {
  14.     class Node {
  15.         int data;
  16.         Node next;
  17.         public Node(int x) {
  18.             data = x;
  19.             next = null;
  20.         }
  21.     }
  22.     Node head; // starting node of linked list
  23.     public void insert_node_at_beginning(int x) {
  24.         if(head == null) {
  25.             head = new Node(x);
  26.             return;
  27.         }
  28.         Node new_node = new Node(x);
  29.         new_node.next = head;
  30.         head = new_node;
  31.     }
  32.     public void insert_node_at_end(int x) {
  33.         if(head == null) {
  34.             head = new Node(x);
  35.             return;
  36.         }
  37.         Node new_node = new Node(x);
  38.         Node tmp = head;
  39.         while(tmp.next != null) {
  40.             tmp = tmp.next;
  41.         }
  42.         tmp.next = new_node;
  43.     }
  44.     public void delete_node(int x) {
  45.         Node current_node = head;
  46.         Node prev_node = null;
  47.         while(current_node != null && current_node.data != x) {
  48.             prev_node = current_node;
  49.             current_node = current_node.next;
  50.         }
  51.         prev_node.next = current_node.next;
  52.     }
  53.     public void print() {
  54.         Node tmp = head;
  55.         while(tmp != null) {
  56.             System.out.print(tmp.data + " --> ");
  57.             tmp = tmp.next;
  58.         }
  59.         System.out.println();
  60.     }
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement