Google

Program to implement Dequeue (Double Ended Queues) using Arrays with front always at zero

Written on:October 2, 2012
Comments are closed

Double Ended Queues (Dequeue)

Program to implement Dequeue (Double Ended Queues) using Arrays with front always at zero

/*Implementation of De-queue using arrays*/

#include <stdio.h>
#include <conio.h>
#include <stdlib.h>

#define MAX 10

typedef struct dequeue
{int front,rear;
int arr[MAX];
}dq;

/*If flag is zero, insertion is done at beginning
else if flag is one, insertion is done at end.
*/
void enqueue(dq *q,int x,int flag)
{
int i;
if(q->rear==MAX-1)
{printf(“nQueue overflow!”);
exit(1);
}
if(flag==0)
{for(i=q->rear;i>=q->front;i–)
q->arr[i+1]=q->arr[i];
q->arr[q->front]=x;
q->rear++;
}
else if(flag==1)
{q->arr[++q->rear]=x;
}
else
{printf(“nInvalid flag value…!”);
return;
}
}

void de_queue(dq *q,int flag)
{int i;
/*front is initialized with zero, then rear=-1
indicates underflow*/
if(q->rear<q->front)
{printf(“nQueue Underflow…!”);
exit(1);
}
if(flag==0)/*deletion at beginning*/
{for(i=q->front;i<=q->rear;i++)
q->arr[i]=q->arr[i+1];
q->arr[q->rear]=0;
q->rear–;
}
else if(flag==1)
{q->arr[q->rear–]=0;
}
else
{printf(“nInvalid flag value…!”);
return;
}
}

void display(dq *q)
{
int i;
for(i=q->front;i<=q->rear;i++)
printf(“%dt”,q->arr[i]);
}

void main()
{
dq q;
q.front=0;
q.rear=-1;
int ch,num;
while(1)
{
clrscr();
printf(“nMenu-Double Ended Queue”);
printf(“nn1. Enqueue – Begin”);
printf(“n2. Enqueue – End”);
printf(“n3. Dequeue – Begin”);
printf(“n4. Dequeue – End”);
printf(“n5. Display”);
printf(“n6. Exit”);
printf(“nnEnter your choice?”);
scanf(“%d”,&ch);
switch(ch)
{
case 1:
printf(“nEnter the number?”);
scanf(“%d”,&num);
enqueue(&q,num,0);
break;
case 2:
printf(“nEnter the number?”);
scanf(“%d”,&num);
enqueue(&q,num,1);
break;
case 3:
printf(“nDeleting element from beginning…!”);
de_queue(&q,0);
break;
case 4:
printf(“nDeleting element from end…!”);
de_queue(&q,1);
break;
case 5:
display(&q);
break;
case 6:
exit(0);
default:
printf(“nInvalid Choice…!”);
}
getch();
}
}

 

Sorry, the comment form is closed at this time.