Program for Doubly Linked
List
#include
<iostream.h>
class
Dlist
{
private:
int
n;
Dlist *next, *prev,*head,*ptr,*pr;
public:
Dlist()
{
head=NULL;
}
void
getData();
void
disp();
void
del();
void
insert();
};
void
Dlist::getData()
{
Dlist
*tmp;
tmp=new
Dlist();
tmp->prev=tmp->next=NULL;
cout<<"\n\tEnter
No :";
cin>>tmp->n;
if(head==NULL)
{
ptr=head=tmp;
}
else
{
tmp->prev=ptr;
ptr->next=tmp;
ptr=tmp;
}
pr=tmp;
}
void
Dlist::disp()
{
Dlist
*tmp;
cout<<"\n\t\tList\t\t";
for(tmp=head;tmp!=NULL;tmp=tmp->next)
{
cout<<tmp->n<<"
- ";
}
tmp=pr;
cout<<"\n\t\tReverse
\t";
for(;tmp!=NULL;tmp=tmp->prev)
{
cout<<tmp->n<<"
- ";
}
cout<<"\n";
}
void Dlist::del()
{
int
num;
Dlist
*tmp,*ptr1;
cout<<"\n\t\t\tNumber
to Delete? ";
cin>>num;
for(tmp=head;tmp!=NULL;tmp=tmp->next)
{
if(tmp->n==num)
{
break;
}
else
{
ptr1=tmp;
}
}
if(tmp==head)
{
head=head->next;
head->prev=NULL;
}
else
if(tmp==NULL)
{
cout<<"\n\t\tNo.
is not Found!...";
}
else
{
ptr1->next=tmp->next;
tmp->next->prev=ptr1;
}
delete(tmp);
}
void
Dlist::insert()
{
int
pos,i=0;
Dlist
*tmp,*ptr1,*ptr2;
if(head==NULL)
{
cout<<"\n
List not created !!!";
}
else
{
tmp=new
Dlist();
tmp->next=tmp->prev=NULL;
cout<<"\n\tPostion
? ";
cin>>pos;
cout<<"\n\tNew
Data : ";
cin>>tmp->n;
ptr1=head;
while(ptr1->next!=NULL)
{
i++;
if(i==pos)
{
break;
}
else
{
ptr2=ptr1;
}
ptr1=ptr1->next;
}
if(ptr1==head)
{
tmp->next=head;
head->prev=tmp;
head=tmp;
}
else
{
cout<<ptr1->n<<" "<<ptr2->n;;
ptr2->next=tmp;
tmp->prev=ptr2;
tmp->next=ptr1;
ptr1->prev=tmp;
}
}
}
int
menu(int ch)
{
cout<<"\n\t\tMain
Menu\n";
cout<<"\n\t[1.]\t
Add";
cout<<"\n\t[2.] \t
Delete";
cout<<"\n\t[3.] \t
Display";
cout<<"\n\t[4.] \t
Insert";
cout<<"\n\t[5.] \t
Exit";
cout<<"\n\tEnter a
Choice : ";
cin>>ch;
return
ch;
}
void main()
{
int ch=0;
Dlist DL;
do
{
ch=menu(ch);
switch(ch)
{
case
1:DL.getData(); break;
case
2:DL.del();break;
case
3:DL.disp();break;
case
4:DL.insert();break;
case
5:cout<<ch<<"Quit . . . .";
}
}while(ch!=5);
}
No comments:
Post a Comment