public class List { private static Node head = null; class Node { int n; Node next; public Node(int n) { this.n = n; this.next = null; } } public void add(int n) { Node l = new Node(n); if(head == null) { head = l; } else { Node l1 = head; while(l1.next != null) { l1 = l1.next; } l1.next = l; } } public void add(int m, int n) { Node node = new Node(n); Node l = head; while(l.n != m) { l = l.next; } Node t = l.next; l.next = node; node.next = t; } public int delete(int n) { Node t = null; Node p = null; Node l = head; if(l.n == n) { t = head; head = head.next; } else { while(l.next != null) { if(l.next.next == null && l.n != n) { t = l.next; l.next = null; break; } else { Node l1 = l.next; if(l.n == n) { t = l; p.next = l1; break; } } p = l; l = l.next; } } return t.n; } public void print() { Node l1 = head; while(l1 != null) { System.out.print(l1.n + " "); l1 = l1.next; } } public static void main(String args[]) { System.out.println("Hi"); List l = new List(); l.add(1); l.add(2); l.add(3); l.add(4); l.print(); System.out.println(); l.add(3,5); l.print(); System.out.println(); l.delete(4); l.print(); } }
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter