Doubly Linked list code in java
public class DLL{
Node head;
Node tail;
public DLL(){
head=null;
tail=null;
}
class Node{
int data;
Node next;
Node prev;
Node(int data){
this.data=data;
next=prev=null;
}
}
// Insertion at Beginning
public void InsertionAtBeginning(int data){
Node newnode=new Node(data);
if (head==null) {
head=newnode;
tail=newnode;
}else{
newnode.next=head;
head.prev=newnode;
head=newnode;
}
}
//Insertion at End
public void InsertionAtEnd(int data){
Node newnode=new Node(data);
if (tail==null) {
head=newnode;
tail=newnode;
}else{
newnode.prev=tail;
tail.next=newnode;
tail=newnode;
}
}
//Deletion at Beginning
public void DeletionAtBeginning(){
if (head==null) {
return;
}
if (head==tail) {
head=null;
tail=null;
return;
}
Node current=head;
head=head.next;
head.prev=null;
current.next=null;
}
//Deletion at End
public void DeletionAtEnd(){
if (tail==null) {
return;
}
if (head==tail) {
head=null;
tail=null;
return;
}
Node current=tail;
tail=tail.prev;
tail.next=null;
current.prev=null;
}
//Traversing Forward
public void ForwardTraversal(){
if (head==null) {
System.out.println("List is Empty");
return;
}
System.out.println("Forward Traversal:-");
Node current=head;
while (current !=null) {
System.out.print(current.data + " --> ");
current=current.next;
}
System.out.println();
}
//Backward Traversal
public void BackwardTraversal(){
if (tail==null) {
System.out.println("List is Empty");
return;
}
System.out.println("Backward Traversal:-");
Node current=tail;
while (current !=null) {
System.out.print(current.data + " --> ");
current=current.prev;
}
System.out.println();
}
public static void main(String[] args) {
DLL dll=new DLL();
dll.InsertionAtBeginning(1);
dll.InsertionAtEnd(2);
dll.InsertionAtEnd(3);
dll.ForwardTraversal();
dll.BackwardTraversal();
dll.DeletionAtBeginning();
dll.DeletionAtEnd();
dll.ForwardTraversal();
dll.BackwardTraversal();
}
}
Nice wow
ReplyDeleteChin tapak dum dum
ReplyDelete