Tuesday 19 May 2015

C program to implement stack and queue using double link list

#include<stdio.h>

struct node
{
int data;
struct node *llink,*rlink;
};

typedef struct node * NODE;


NODE insert_rear(NODE head)
{
NODE tmp,cur;
int item;
tmp=(NODE)malloc(sizeof(struct node));
printf("\n Enter the data to insert : ");
scanf("%d",&item);
tmp->data=item;
tmp->rlink=NULL;
tmp->llink=NULL;
if(head->rlink == NULL)
{
head->rlink=tmp;
tmp->llink=head;
return(head);
}
cur=head->rlink;
while(cur->rlink != NULL)
cur=cur->rlink;
cur->rlink=tmp;
tmp->llink=cur;
return(head);
}

NODE del_front(NODE head)
{
NODE cur,tmp;
if(head->rlink == NULL)
{
printf("\n List is empty.\n");
return(head);
}
tmp=head->rlink;
if(tmp->rlink==NULL)
{
printf("\n You have deleted %d \n",tmp->data);
free(tmp);
head->rlink=NULL;
return(head);
}
cur=tmp->rlink;
head->rlink=cur;
cur->llink=head;
printf("\n You have deleted %d \n",tmp->data);
free(tmp);
return(head);
}

NODE del_rear(NODE head)
{
NODE cur,tmp;
if(head->rlink == NULL)
{
printf("\n List is empty.\n");
return(head);
}
tmp=head->rlink;
if(tmp->rlink==NULL)
{
printf("\n You have deleted %d \n",tmp->data);
free(tmp);

head->rlink=NULL;
return(head);
}
while(tmp->rlink != NULL)
tmp=tmp->rlink;
cur=tmp->llink;
printf("\n You have deleted %d \n",tmp->data);
free(tmp);
cur->rlink=NULL;
return(head);
}

display(NODE head)
{
NODE cur;
if(head->rlink == NULL)
{
printf("\n List is empty.\n");
return(head);
}
cur=head->rlink;
while(cur != NULL)
{
printf("%d \t",cur->data);
cur=cur->rlink;
}
printf("\n");
}

main()
{
NODE head;
int opt,opt1,opt2;
head=(NODE)malloc(sizeof(struct node));
head->data=0;
head->llink=NULL;
head->rlink=NULL;

while(1)
{
printf("\n -------------MENU------------- \n");
printf(" 1. STACK \n 2. QUEUE \n");
printf(" Enter your option : ");
scanf("%d",&opt);
if(opt == 1)
{
while(1)
{
printf("\n 1. Push \n 2. Pop \n 3. Display \n 4. Exit \n");
printf("\n Enter your option for stack : ");
scanf("%d",&opt1);
switch(opt1)
{
case 1 : head=insert_rear(head);
break;

case 2 : head=del_rear(head);
break;

case 3 : display(head);
break;

case 4 : exit(0);
break;

default : printf("\n Invalid choice.\n");

}
}
}

else if(opt == 2)
{
while(1)
{
printf("\n 1. Insert Rear \n 2. Delete Front \n 3. Display \n 4. Exit \n");
printf(" \n Enter your option for queue : ");
scanf("%d",&opt2);
switch(opt2)
{
case 1 : head=insert_rear(head);
break;

case 2 : head=del_front(head);
break;

case 3 : display(head);
break;

case 4 : exit(0);
break;

default : printf("\n Invalid choice. \n");

}
}
}

else
{
exit(0);
}


}
}

No comments:

Post a Comment