Page

C++ Program to Implement Doubly Link List

#include <iostream.h>
#include <process.h>

class doubly
{
doubly * next;
doubly * pre;
int data,ch;
public:
doubly * link(doubly * );
void traverse (doubly * );
};

doubly * doubly::link(doubly * temp)
{
doubly * newlink;
doubly * cur;
newlink = new doubly;
cout<<"\nEnter Element (only possitive number):";
cin>>data;
cur = temp;
if(temp == NULL)
{
newlink->data = data;
newlink->pre = NULL;
newlink->next = NULL;
temp = newlink;
return temp;
}

else
{
while(cur->next != NULL)
{
cur = cur->next ;
}
newlink->data = data;
newlink->pre = cur;
newlink->next = NULL;
cur->next = newlink;
return temp;
}
}


void doubly::traverse(doubly *temp)
{
int ch;
doubly * dummy;
dummy = temp;
cout<<"\n[1] Start From Begainning\n[2] Start From End\n";
cout<<"\nEnter Your Choice  :";
cin>>ch;
switch(ch)
{
case 1:
if(dummy != NULL)
{
while(temp->next !=NULL)
{
cout<<temp->data<<endl;
temp=temp->next;
}
if (temp->next == NULL)
cout<<temp->data<<endl;
}
break;
case 2:
if(temp != NULL)
{
temp = dummy;
while(dummy->next !=NULL)
{
dummy=dummy->next;
}
while(dummy->pre !=NULL)
{
cout<<dummy->data<<endl;
dummy=dummy->pre;

}
if (dummy->pre == NULL)
cout<<dummy->data<<endl;
}
break;
}
}

void main()
{
doubly *first=NULL,d1;
int choice;
while(1)
{
cout<<"\n************** DOUBLY LINK LIST **************\n\n";
cout<<"Choices Are :-\n=>[1] For Insert \n=>[2] For Traverse \n=>[3] For Exit";
cout<<"\n\nEnter Your choice : ";
cin>>choice;

switch (choice)
{
case 1:
first=d1.link(first);
break;

case 2:
d1.traverse(first);
break;
case 3:
exit(0);

}

}
}

No comments:

Post a Comment