A deque is a data structure that allows both deletion as well as insertion of elements to be done at both ends of a queue.
Implement a deque using a circular array.
Difficulty level
Video recording
This exercise is mostly suitable for students
#define N 10
#include<stdio.h>
#include<stdlib.h>
typedef int element;
typedef struct
{
element data[N];
int front;
int rear;
} Deque;
Deque CreateDeque()
{
Deque q;
q.front = 1; q.rear=0;
return q;
}
int isFullDeque(Deque q)
{
return (q.front == (q.rear+2)%N);
}
int isEmptyDeque(Deque q)
{
return (q.front == (q.rear+1)%N);
}
int insertFront(Deque *q, element e)
{
if(isFullDeque(*q)) return 0;
q->front = (q->front-1+N)%N;
q->data[q->front] = e ;
return 1;
}
int insertRear(Deque *q, element e)
{
if(isFullDeque(*q)) return 0;
q->rear = (q->rear+1)%N;
q->data[q->rear] = e ;
return 1;
}
int deleteFront(Deque *q)
{
if (isEmptyDeque(*q)) return 0;
q->front = (q->front+1)%N;
return 1;
}
int deleteRear(Deque *q)
{
if (isEmptyDeque(*q)) return 0;
q->rear = (q->rear-1+N)%N;
return 1;
}
int Front(Deque q, element *e)
{
if (isEmptyDeque(q)) return 0;
*e = q.data[q.front];
return 1;
}
int Rear(Deque q, element *e)
{
if (isEmptyDeque(q) ) return 0;
*e = q.data[q.rear];
return 1;
}
void print(Deque d)
{
element e;
printf("FRONT --> ");
while(Front(d,&e))
{
deleteFront(&d);
printf("%d ",e);
}
printf("<-- REAR\n\n");
}
void test1()
{
Deque d ;
element e;
int i;
d=CreateDeque();
for(i=10;i<=30;i+=2)
{
insertFront(&d,i);
insertRear(&d,i+1);
print(d);
}
for(i=10;i<=30;i+=2)
{
deleteFront(&d);
deleteRear(&d);
print(d);
}
}
int main()
{
test1();
return 0;
}
Back to the list of exercises
Looking for a more challenging exercise, try this one !!
Heap of prime factors