Thursday 7 November 2013

c++ program for operations on doubly linked lists

#include<iostream.h>
#include<conio.h>
#include<malloc.h>
struct node
{
int data;
node *plink,*slink;
};
struct node *head=NULL;
void insbeg(int key)
{
if(head==NULL)
{
head=new node;
head->data=key;
head->plink=NULL;
head->slink=NULL;
}
else
{
node *p;
p=new node;
p->data=key;
p->slink=head;
p->plink=NULL;
head->plink=p;
head->plink->slink=p;
head=p;
}
}
void insend(int key)
{
if(head==NULL)
{
head=new node;
head->data=key;
head->plink=NULL;
head->slink=NULL;
}
else
{
node *temp=head;
while(temp->slink!=NULL)
{
 temp=temp->slink;
}
node *temp2;
temp2=new node;
temp->slink=temp2;
temp2->slink=NULL;
temp2->plink=temp;
temp2->data=key;
}
}
void del(int key)
{
if(head->data==key)
{
node *temp=head;
head=head->slink;
head->plink=head;
temp->slink=temp->plink=head;
free(temp);
}
else
{
struct node *temp=head;
while(temp->slink->data!=key)
{
temp=temp->slink;
}
struct node *temp2=temp->slink;
temp->slink=temp2->slink;
temp->slink->plink=temp;
temp2->slink=temp2->plink=head;
free(temp2);
}
}
void display()
{
if(head==NULL)
{
cout<<"list empty:";
}
else
{
node *temp=head;
while(temp!=NULL)
{
cout<<"\t"<<temp->data;
temp=temp->slink;
}
}
}

void main()
{
int val,n,z;
clrscr();
do
{
cout<<"1.ins @ beg 2. ins @ end 3.del any node 4.display";
cin>>n;
switch(n)
{
 case 1:cout<<"enter the data to be inserted:";
cin>>val;
insbeg(val);break;
 case 2:cout<<"enter the data to be inserted:";
cin>>val;insend(val);break;
 case 3:cout<<"enter the data to be deleted:";
cin>>val;del(val);break;
 case 4:display();
}
cout<<"1.continue 2.no";
cin>>z;
}while(z!=2);
  getch();
}

No comments:

Post a Comment