Thursday, January 29, 2015

dqueue using linkedlist

#include< stdio.h>

typedef struct dqueue
{
 int data;
 struct dqueue *left,*right;
}list;

list *front, *rear;

int choice,element;

list *add_front(list *);
list *add_rear(list *);
list *delete_front(list *);
list *delete_rear(list *);
void display(list *,list *);
int count(list *);



void main()
{
 front=(list *)malloc(sizeof(list));
 rear=(list *)malloc(sizeof(list));

 front->left=NULL;
 rear->right=NULL;

 front->right=rear;
 rear->left=front;

 while(1)
 {
  choice=menu();
  switch(choice)
  {
   case 1: front=add_front(front);   break;
   case 2: rear=add_rear(rear);   break;
   case 3: front=delete_front(front);break;
   case 4: rear=delete_rear(rear);   break;
   case 5: display(front,rear); getch();break;
   case 6: printf("\nno of items in dqueue : %d\n",count(front));getch();break;
   case 7: exit();
   default : printf("\nInvalid option...\n");getch();
  }
 }
}

int menu()
{
 clrscr();
 printf("Queue elements : \n\n");
 display(front,rear);
 printf("\n\nMENU\n---------------------\n1. add item at front\n2. add item at back");
 printf("\n3. delete item from front\n4. delete item from rear\n5. display items\n6. count items\n7. exit");

 printf("\nenter your choice : ");
 scanf("%d",&choice);
 return choice;
}

list *add_front(list *front)
{
 list *temp;
 temp=(list *)malloc(sizeof(list));
 
 if(temp==NULL)
 {
  printf("\nInsufficient Memory...\n");
  getch();
  return;
 }
 else
 {
  printf("\nenter element to add at front : ");
  scanf("%d",&element);
  front->data=element;
  front->left=temp;
  temp->right=front;
  temp->left=NULL;
  front=temp;
 }
 return (front);

}

list *add_rear(list *rear)
{
 list *temp;
 temp=(list *)malloc(sizeof(list));

 if(temp==NULL)
 {
  printf("\nInsufficient Memory...\n");
  getch();
  return;
 }
 else
 {
  printf("\nenter element to add at rear : ");
  scanf("%d",&element);
  rear->data=element;
  rear->right=temp;
  temp->left=rear;
  temp->right=NULL;
  rear=temp;
 }
 return (rear);

}

list *delete_front(list *front)
{
 list *temp;
 temp=front->right->right;

 free(front->right);
 front->right=temp;
 front->right->left=front;
 return (front);
}

list *delete_rear(list *rear)
{
 list *temp;
 temp=rear->left->left;

 free(rear->left);
 rear->left=temp;
 rear->left->right=rear;
 return (rear);
}

void display(list *front,list *rear)
{
 list *temp;
 if(count(front)==0)
 {
  printf("\n<---- Dqueue Empty ---->\n");
  return;
 }
 else
 {
  printf("displaying left -> right :\n");
  temp=front->right;
  while(temp->right!=NULL)
  { printf("%d ",temp->data);temp=temp->right;}
  printf("\ndisplaying left <- right :\n");
  temp=rear->left;
  while(temp->left!=NULL)
  { printf("%d ",temp->data);temp=temp->left;}
 }
}

int count(list *front)
{
 if(front->right->right==NULL)
  return 0;
 else
  return (1+count(front->right));
}

No comments:

Post a Comment