Run Code
|
API
|
Code Wall
|
Misc
|
Feedback
|
Login
|
Theme
|
Privacy
|
Patreon
Linked List creation
//'main' method must be in a class 'Rextester'. //Compiler version 1.8.0_111 import java.util.*; import java.lang.*; class Node{ int data; Node next; Node(int data){ this.data = data; this.next=null; } } class Rextester { Node head=null; public void insertFirst(int data){ if(head==null){ Node n = new Node(data); head = n; return; } else{ Node n = new Node(data); n.next = head; head = n; return; } } public void insertLast(int data){ if(head==null){ Node n = new Node(data); head = n; return; } else{ Node n = new Node(data); Node pre = head; while(pre.next!=null){ pre = pre.next; } pre.next = n; } } public void insert(int data,int pos){ Node ne = head; int count=0; while(count<pos-1){ count++; ne = ne.next; } Node n = new Node(data); n.next = ne.next; ne.next = n; } public void display(){ Node n = head; while(n!=null){ System.out.println(n.data); n = n.next; } } public void deleteFirst(){ if(head==null){ System.out.println("Empty lIst"); } else{ Node n = head; head = n.next; } } public void deleteLast(){ if(head==null){ System.out.println("Empty list"); } else{ Node n = head; Node pre = null; while(n.next!=null){ pre = n; n = n.next; } pre.next = null; } } public void delete(int pos){ Node n = head; Node pre = null; int count=0; while(count!=pos-1){ count++; pre = n; n = n.next; } pre.next = n.next; } public static void main(String args[]) { Rextester r = new Rextester(); r.insertFirst(1); r.insertLast(10); r.insert(2,2); r.insertLast(20); r.deleteFirst(); r.deleteLast(); r.delete(2); r.display(); } }
run
|
edit
|
history
|
help
0
Coloring map
2c
javaLP
jb14 isEven Links
2A
3.A
Abhay
Java 8... lambda, streams und so...
jb6.6 str rec
Ab