Double linked list c++

Program to implement double linked list in C++ with the member functions
1 : To insert a node at a specified position
2 : Delete a node at specified position
3 : Display the list after every peration
Note that the first two inputs to the list must be done to position 1..


#include<iostream.h>
#include<conio.h>
#include<stdlib.h>
class dll
{
struct node
{
int info;
struct node *left,*right;
};
typedef struct node *nodeptr;
nodeptr list;
public: dll()
{
list=NULL;
}
void ins_pos(int,int);
void del_pos(int);
void display();
};
void dll::ins_pos(int x,int pos)
{
nodeptr p,q;
int count=0,i;
p=new node;
p->left=NULL;
p->right=NULL;
p->info=x;
if(list==NULL)
{
list=p;
}
else
if(pos==1)
{
p->right=list;
list=p;
}
else
{
for(q=list;q->right!=NULL;q=q->right)
count++;
if(pos<=count+1)
{
q=list;
for(i=1;i<pos-1;i++)
q=q->right;
(q->right)->left=p;
p->right=q->right;
q->right=p;
p->left=q;
}
}
cout<<"\n"<<x<<" inserted @ "<<pos<<" position..!";
display();
}
void dll::display()
{
nodeptr p;
if(list==NULL)
cout<<"\nInvalid operation..!";
else
{
cout<<"\n\nDLL elements\n--------------";
for(p=list;p!=NULL;p=p->right)
cout<<"\n"<<p->info;
cout<<"\n\n";
}
}
void dll::del_pos(int pos)
{
int count=0,x,i;
nodeptr p,q;
if(list==NULL)
cout<<"\nInvalid operation..!";
else
if(pos==1)
{
p=list;
list=list->right;
x=p->info;
delete p;
cout<<"\n"<<x<<" deleted form position "<<pos;
display();
}
else
{
for(p=list;p!=NULL;p=p->right)
count++;
if(pos<=count)
{
p=list;
for(i=1;i<pos-1;i++)
p=p->right;
q=p->right;
p->right=q->right;
(q->right)->left=p;
x=q->info;
delete(q);
cout<<"\n"<<x<<" deleted form position "<<pos;
display();
}
}
}

main()
{
int ele,pos,c;
dll l;
clrscr();
while(1)
{
cout<<"\n1 : Insert element @ a position??\n2 : Delete element from a position??\n3 : Exit??\n";
cout<<"Reply pls.. ";cin>>c;
switch(c)
{
case 1:cout<<"Enter the value and position : ";
cin>>ele>>pos;
l.ins_pos(ele,pos);
break;
case 2:cout<<"\nEnter the position : "; cin>>pos;
l.del_pos(pos);
break;
case 3:exit(0);
break;
}
}
getch();
return 0;
}
Category:

0 comments: