C++ PROGRAM FOR DOUBLY LINKED LIST


#include<iostream.h>
#include<conio.h>
class dblist
{
private:
struct node
{
node *flink;
int data;
node *blink;
} *p;
public:
dblist():p(NULL)
{}
~dblist();
void addbeg(int);
void addend(int);
void addafter(int,int);
void dblistshow();
void del(int);
int dblistcount();
};
void dblist::addend(int n)
{
node *q,*t;
if(p==NULL)
{
p=new node;
p->flink=NULL;
p->data=n;
p->blink=NULL;
}
else
{
q=p;
while(q->blink!=NULL)
q=q->blink;
t=new node;
t->flink=q;
t->data=n;
t->blink=NULL;
q->blink=t;
}
}
void dblist::addbeg(int n)
{
node *q;
q=new node;
q->flink=NULL;
q->data=n;
q->blink=p;
p->flink=q;
p=q;

}
void dblist::addafter(int c,int n)
{
node *q,*t;
int i;
for(i=0,q=p;i<c;i++)
{
if(q==NULL)
{
cout<<"there are less than"<<c<<"elements"<<endl;
return;
}
}
t=new node;
t->flink=q;
t->data=n;
t->blink=q->blink;
q->blink=t;
}
void dblist::del(int n)
{
node *q,*r,*s;
q=p;
if(q->data==n)
{
p=q->blink;
p->flink=NULL;
delete q;
return;
}
r=q;
s=q->blink;
while(q!=NULL)
{
if(q->data==n)
{
r->blink=q->blink;
s->flink=q->flink;
return;
}
r=q;
q=q->blink;
}
cout<<"element"<<n<<"not in the list"<<endl;
}
void dblist::dblistshow()
{
node *q;
for(q=p;q!=NULL;q=q->blink)
cout<<q->data<<endl;
}
int dblist::dblistcount()
{
node *q;
int c=0;
for(q=p;q!=NULL;q=q->blink)
c++;
return c;
}
dblist::~dblist()
{
node *q;
if(p==NULL)
return;
while(p!=NULL)
{
q=p->blink;
delete p;
p=q;
}
}
void main()
{
dblist l1;
int ch,item,after;
clrscr();
do
{
cout<<"**********DOUBLY LINKED LIST*********\n";
cout<<"\n 1.ADD AT BEGINNING"<<endl;
cout<<"\n 2.ADD AT END"<<endl;
cout<<"\n 3.ADD AFTER"<<endl;
cout<<"\n 4.SHOW LIST"<<endl;
cout<<"\n 5.COUT LIST"<<endl;
cout<<"\n 6.DELETE NODES"<<endl;
cout<<"\n 7.QUIT"<<endl;
cout<<"Enter your choice(1-7)";
cin>>ch;
switch(ch)
{
case 1:
cout<<"enter the node value";
cin>>item;
l1.addbeg(item);
l1.dblistshow();
break;
case 2:
cout<<"enter the node value";
cin>>item;
l1.addend(item);
l1.dblistshow();
break;
case 3:
cout<<"enter the node value";
cin>>item;
cout<<"entert after which node....";
cin>>after;
l1.addafter(after-1,item);
l1.dblistshow();
break;
case 4:
l1.dblistshow();
case 5:
item=l1.dblistcount();
cout<<"total nodes in the list:"<<item<<endl;
break;
case 6:
cout<<"enter the node value to be deleted:";
cin>>item;
l1.del(item);
l1.dblistshow();
break;
case 7:
break;
}
getch();
}while(ch!=7);
}


OUTPUT:
 1.ADD AT BEGINNING
 2.ADD AT END
 3.ADD AFTER
 4.SHOW LIST
 5.COUT LIST
 6.DELETE NODES
 7.QUIT

Enter your choice(1-7)4
20
40
10
70
total nodes in the list:4
**********DOUBLY LINKED LIST*********

 1.ADD AT BEGINNING
 2.ADD AT END
 3.ADD AFTER
 4.SHOW LIST
 5.COUT LIST
 6.DELETE NODES
 7.QUIT
Enter your choice(1-7)6
enter the node value to be deleted:3
element3not in the list
20
40
10
70

No comments:

Post a Comment