Doubly Linked List - Java
import java.util.*;
class Nodes
{
int data;
Nodes llink,rlink;
}
class Dlink
{
Nodes first=null;
Nodes last=null;
int nd=0;
Scanner s=new Scanner(System.in);
void add()
{
Nodes node=new Nodes();
node.llink=null;
node.rlink=null;
System.out.println("Enter data");
node.data=s.nextInt();
if(first==null) first=last=node;
else { last.rlink=node;node.llink=last; last=node;}
nd++;
}
void disp()
{
Nodes t=new Nodes();
System.out.println("1.Left to right or 2.right to left...");
int op=s.nextInt();
if(op==1)
{
t=first;
while(t!=null)
{
System.out.print(t.data + "<--->" );
t=t.rlink;
}
}
else
{
t=last;
while(t!=null)
{
System.out.print(t.data + "<--->" );
t=t.llink;
}
}
System.out.println("NULL\n");
}
void search()
{
System.out.println("Enter data...");
int d=s.nextInt();
Nodes t=first;int p=1;boolean found=false;
while(t!=null)
{
if(t.data==d) {found=true;break;}
t=t.rlink;
p++;
}
if(found) System.out.println("Found at pos ..."+ p );
else System.out.println("Not found");
}
void del()
{
System.out.println("Enter the pos........");
int p=s.nextInt();
if(p>nd) System.out.println("Invalid position");
else
{
if(p==1) { first=first.rlink;
if(first==null) last=null; else first.llink=null;nd--;}
else
if(p==nd) { last=last.llink;
if(last==null) first=null;
else last.rlink=null;nd--;}
else
{
Nodes t=first;int i=2;
while(i<p) {t=t.rlink;i++;}
Nodes tmp=t.rlink.rlink;
t.rlink=tmp;
tmp.llink=t;
nd--;
}
}
}
}
class Main
{
public static void main(String args[])
{
Scanner s=new Scanner(System.in);
int op;
Dlink dl=new Dlink();
while(true)
{
System.out.println("1.add\n2.disp\n3.search\n4.del\n5.exit\n Enter Option");
op=s.nextInt();
switch(op)
{
case 1: dl.add();
break;
case 2: dl.disp();
break;
case 3: dl.search();
break;
case 4: dl.del();
break;
case 5:System.exit(0);
}
}
}
}
Comments
Post a Comment