Aim
Linked List Operation like:
- Insertion at first
- Insertion at last
- Deletion at first
- Deletion at last
- Display
Source Code:
import
java.util.*;
class
LL {
Node head;
class Node{
String data;
Node next;
Node(String data){
this.data = data;
this.next = null;
}
}
public void addFirst(String data){
Node newNode = new Node(data);
if(head == null){
head = newNode;
return;
}
newNode.next = head;
head = newNode;
}
public void addlast(String data){
Node newNode = new Node(data);
if(head == null){
head = newNode;
return;
}
Node currNode = head;
while(currNode.next!=null){
currNode = currNode.next;
}
currNode.next = newNode;
}
public void printList(){
Node currNode = head;
while(currNode!=null){
System.out.print(currNode.data +
"->");
currNode = currNode.next;
}
System.out.println("NULL");
}
public void deleteFirst(){
if(head == null){
System.out.println("this list
is empty");
return;
}
head = head.next;
}
public void deleteLast(){
if(head == null){
System.out.println("this list
is empty");
return;
}
if(head.next == null){
head = null;
return;
}
Node secondLast = head;
Node lastNode = head.next;
while(lastNode.next != null){
lastNode = lastNode.next;
secondLast = secondLast.next;
}
secondLast.next = null;
}
public static void main(String[] args) {
LL list = new LL();
list.addFirst("a");
System.out.print("1.Insert at
start\n");
System.out.print("2.Insert at
end\n");
System.out.print("3.Delete at
start\n");
System.out.print("4.Delete at
end\n");
System.out.print("5.Display\n");
Scanner sc=new Scanner(System.in);
int ch= sc.nextInt();
switch(ch){
case 1:
list.addFirst("is");
list.printList();
System.out.print("Insert at first Successfully\n");
break;
case 2:
list.addlast("linked
List");
list.printList();
System.out.println("Insert at last Successfully\n");
break;
case 3:
list.deleteFirst();
list.printList();
System.out.println("Deleted at first Successfully");
break;
case 4:
list.deleteLast();
list.printList();
System.out.println("Deleted at first Successfully");
break;
case 5:
list.printList();
break;
default:
System.out.println("Invalid Input");
}
}