Friday, August 31, 2012

C Program for Double Linked List

#include<iostream.h>
#include<alloc.h>
#include<conio.h>
struct node
{
  int item;
  struct node *n,*p;
}*a;
void create(struct node *q)
{
     int choice;
     cout<<"Enter value";
     cin>>q->item;
     cout<<"Do you Want to Continue 1.YES/2.NO";
     cin>>choice;
     if(choice==1)
     {

          q->n=(node*)malloc(sizeof(node));
          q->n->p=q;
          create(q->n);
     }
     else
     {
          q->n=NULL;
     }
}
void print(struct node *q)
{
     if(q==NULL)return;
     cout<<"       "<<q<<"\t"<<q->p<<"\t"<<q->item<<"\t"<<q->n<<endl;
     print(q->n);
}
void del(struct node *q,int x)
{
    while(q->item!=x)
    q=q->n;
    if(q->p==NULL)       //First node.
    {
     q->n->p=NULL;
     a=q->n;
     return;
    }
    if(q->n==NULL)       //Last node.
    {
     q->p->n=NULL;
     return;
    }                     //Intermediate value.
    q->p->n=q->n;
    q->n->p=q->p;
     free (q);
}
void ins(struct node *q,int loc,int value)
{
    struct node *t;
    t=(node*)malloc(sizeof(node));
    t->item=value;
    if(loc==1)             //first
    {
    t->n=q;
    t->p=NULL;
    q->p=t;
    a=t;
    return;
    }
    for(int i=1;i<=loc;i++)
    q=q->n;
    if(q->n==NULL)         //Last
    {
     q->n=t;
     t->p=q;
     t->n=NULL;
    }
    else                   //Intermediate
    {
    t->n=q->n;
    t->p=q;
    q->n->p=t;
    t->n=t;
    }
}
void main()
{
 clrscr();
 cout<<"\n****************************************************************n";
 cout<<"\n Program on Double Link List\n";
 cout<<"\n****************************************************************n";
 a=(node*)malloc(sizeof(node));
 a->p=NULL;
 cout<<"\n===========================================================\n";
 create(a);
 cout<<"\n===========================================================\n";
 cout<<"\n      Address of node    Pre node     Value     Next node\n";
 cout<<"\n===========================================================\n";
 print(a);
 cout<<"\n===========================================================\n";
 cout<<"Enter value to delete";
 int x;
 cin>>x;
 del(a,x);
 cout<<"\n===========================================================\n";
 cout<<"\n      Address of node    Pre node     Value     Next node\n";
 cout<<"\n===========================================================\n";
 print(a);
 cout<<"\n===========================================================\n";
 cout<<"Enter location and value";
 int y;
 cin>>x>>y;
 ins(a,x,y);
 cout<<"\n===========================================================\n";
 cout<<"\n      Address of node    Pre node     Value     Next node\n";
 cout<<"\n===========================================================\n";
 print(a);
 cout<<"\n===========================================================\n";
 getch();
}

No comments:

Post a Comment