Search This Blog

Saturday, 10 November 2012

Creation, insertion and deletion in 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 delete(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=1;
t->data=n;
q->blink=t;
t->blink=NULL;
}
}
void dblist::addbeg(int n)
{
node *q;
q=new node;
q->flink=NULL;
q->data=n;
q->blink=p;
p=q;
}
void dblist::addafter(int c,int n)
{
node *q,*t;
int i;
for(i=0;q=p,i<c;i++)
{
q=q->blink;
if(q==NULL)
{
cout<<"there are less then"<<c<<"element"<<endl;
return;
}
}
t=new node;
t->flink=q;
t->data=n;
t->blink=q->blink;
q->blink=t;
}
void dblist::delete(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){
s->flink=q->flink;
delete q;
return;
}
r=q;
q=q->blink;
}
cout<<"element not in the list";
}
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=q->blink;
delete p;
p=q;
}
}
void main()
{
dblist db;
int ch,item,after;
clrscr();
cout<<"\n\tcreation,insertion,deletion of doubly linked";
cout<<"\n\t****************************************";
cout<<"\n\t 1.ADD AT BEGINNING";
cout<<"\n\t 2.ADD AT END";
cout<<"\n\t 3.ADD AT AFTER";
cout<<"\n\t 4.SHOWLIST";
cout<<"\n\t 5.COUNTING NODES IN LIST";
cout<<"\n\t 6.DELETE NODES";
cout<<"\n\t 7.PRESS ANY KEY TO CONTINUE\n";
do {
cout<<"\n\tenter your choice(1-7):";
cin>>ch;
switch(ch){
case 1:
cout<<"\n\tenter the node value:";
cin>>item;
db.addbeg(item);
break;
case 2:
cout<<"\n\tenter node value:";
cin>>item;
db.addend(item);
break;
case 3:
cout<<"\n\tenter the node value:";
cin>>item;
cout<<"\n\tenter the node value:";
cin>>item;
cout,<"\n\tenter after which node:";
cin>>after;
db.addafter(after=1,item);
break;
case 4:
db.dblistshow();
break;
case 5:
item=db.dblistcount();
cout<<"\n\ttotal nodes in the list:"<<item<<endl;
break;
case 6:
cout<<"\n\tenter the node value to be deleted:";
cin>>item;
db.delete(item);
break;
case 7:
cout<<"\n\tBYE";
break;
}
while(ch!=7);
getch();
}
 

Output:
1.ADD AT BEGINNING
2.ADD AT END
3.ADD AT AFTER
4.SHOWLIST
5.COUNTING NODES IN LIST
6.DELETE NODES
7.PRESS ANY KEY TO CONTINUE

enter your choice(1-7):1
enter the node value:10
enter the your choice(1-7):1
enter the node value:20
enter your choice(1-7):6
enter the node value to be deleted:10
enter your choice(1-7):5
total nodes in the list:1
enter your choice(1-7):7
BYE


No comments:

Post a Comment