#include<iostream.h>
struct node
{
int data;
struct node *pre,*nxt;
};
typedef struct node db;
db *head=NULL;
void addfront();
void addafter();
void addbefore();
void display();
void delnode();
main()
{
int ch;
char c;
do
{
cout<<"\nDOUBLY LINKED LIST\n";
cout<<"The choices are:\n1.Insert at the beginning\n2.Insert after\n3.Insert before\n4.Display\n5.Delete a node\n6.Exit";
cout<<"\nEnter a choice:";
cin>>ch;
switch(ch)
{
case 1:
addfront();
break;
case 2:
addafter();
break;
case 3:
addbefore();
break;
case 4:
display();
break;
case 5:
delnode();
break;
case 6:
exit(0);
default:
cout<<"Invalid choice\n";
break;
}
cout<<"\nDo you want to continue?:";
cin>>c;
}
while(c=='y'||c=='Y');
}
void addfront()
{
db *np;
np=new node;
cout<<"Enter the data:";
cin>>np->data;
if(head==NULL)
{
np->nxt=head;
np->pre=NULL;
head=np;
}
else
{
np->nxt=head;
np->pre=NULL;
(np->nxt)->pre=np;
head=np;
}
}
void addafter()
{
db *np,*i;
int loc;
cout<<"\nAfter which item you want to insert?:";
cin>>loc;
np=new node;
cout<<"\nEnter the data:";
cin>>np->data;
for(i=head;i->data!=loc;i=i->nxt);
np->nxt=i->nxt;
np->pre=i;
if(i->nxt!=NULL)
(i->nxt)->pre=np;
i->nxt=np;
}
void addbefore()
{
db *np,*i;
int loc;
cout<<"\nBefore which item you want to insert?:";
cin>>loc;
np=new node;
cout<<"\nEnter the data:";
cin>>np->data;
for(i=head;i->data!=loc;i=i->nxt);
if(i==head)
{
np->nxt=i;
i->pre=np;
head=np;
np->pre=NULL;
}
else
{
np->nxt=i;
np->pre=i->pre;
(i->pre)->nxt=np;
i->pre=np;
}
}
void display()
{
db *i;
cout<<"The items in the list are:\n";
for(i=head;i->nxt!=NULL;i=i->nxt)
cout<<" "<<i->data;
cout<<" "<<i->data;
}
void delnode()
{
db *i;
int loc;
if(head==NULL)
cout<<"\nThe list is empty";
else
{
cout<<"\nEnter the item to be deleted:";
cin>>loc;
for(i=head;i->data!=loc;i=i->nxt);
cout<<"The deleted item is "<<i->data;
if(i==head)
{
head=i->nxt;
head->pre=NULL;
}
else
if(i->nxt==NULL)
{
(i->pre)->nxt=NULL;
}
else
{
(i->pre)->nxt=i->nxt;
(i->nxt)->pre=i->pre;
}
}
}
0 comments:
Post a Comment