Breaking News
Loading...

Doubly linkked list insert , delete, any position using c++

#include<iostream.h>
#include<conio.h>
#include<process.h>
class list
{
 struct dlist
  {
   int data;
    struct dlist *left_link,*right_link;
  };
struct dlist *head;
public:
list(){head=NULL;}
void add(int pos,int i);
void del();
void dis();
};

void list::add(int pos,int i)
{
   struct dlist *temp,*p;
   temp=new dlist;
   temp->data=i;
   temp->left_link=temp->right_link=NULL;
   switch(pos)
   {
   case 1:  temp->right_link=head;
        head=temp;
        break;
   case 2:
        p=head;
        while(p->right_link!=NULL)
        p=p->right_link;
        p->right_link=temp;
        temp->left_link=p;
        break;

   case 3:
       cout<<"Enter position";
       int pos;
       cin>>pos;
       p=head;
       for(int i=2;i<pos;i++)
         p=p->right_link;
       temp->right_link=p->right_link;
       p->right_link=temp;
       temp->left_link=p;
       temp->right_link->left_link=temp;
       break;
      }

}
void list::dis()
{
 struct dlist *temp;
 temp=head;
 while(temp!=NULL)
 {
 cout<<temp->data;
 temp=temp->right_link;
 }
 getch();
}
void list::del()
{
 struct dlist *temp;
cout<<"1 to first\n2 to last\n3 to any pos";
int pos;
cin>>pos;
temp=head;
switch(pos)
{
    case 1: head=temp->right_link;
        delete(temp);
        break;
    case 2:
        while(temp->right_link!=NULL)
        temp=temp->right_link;
        temp->left_link->right_link=NULL;
        delete(temp);
        break;
    case 3:
        cout<<"Enter position";
        int ps;
        cin>>ps;
        for(int i=2;i<ps;i++)
        temp=temp->right_link;
        temp->right_link= temp->right_link->right_link;
        temp->right_link->left_link=temp;
        break;
}
}

void main()
{
int ch;
list s;
while(1)
{ clrscr();
cout<<"\n1 to insert"<<"\n2 to delete"<<"\n3 to display"<<"\n4 to exit";
cin>>ch;
switch(ch)
{
case 1: cout<<"1 to first pos\n2 to last pos\n3 to any pos\n";
    int pos,item;
    cin>>pos;
    cout<<"Enter element:";
    cin>>item;
    s.add(pos,item);
    break;

case 2: s.del();
    break;
case 3:
    s.dis();
    break;
case 4:
    exit(0);
}
}
}

0 comments:

Post a Comment

 
Toggle Footer