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.
Consider the following code:
\(
\texttt{typedef $\cdots$ element ;}\\
\texttt{struct cell \{ element data; struct cell *next; \}}\\
\texttt{typedef struct \{ struct cell *front, *rear; \} deque;}
\)
\(\underline{\textbf{Implement}}\) the following operations \(\texttt{delete_rear}\) and \(\texttt{delete_front}\) that delete the rear (resp. front) element of a deque.
Difficulty level
Video recording
This exercise is mostly suitable for students
#include <stdio.h>
#include <stdlib.h>
typedef int element ;
struct cell {
element data;
struct cell *next;
};
typedef struct {
struct cell *front, *rear;
} deque;
deque CreateDeque()
{
deque d;
d.front = d.rear = NULL ;
return d;
}
int isEmptyDeque(deque d)
{
return d.front==NULL;
}
int EnqueueRear (deque *d, element item )
{
struct cell *temp ;
temp = ( struct cell * ) malloc ( sizeof ( struct cell ) );
if(!temp) return 0;
temp -> data = item ;
temp -> next = NULL ;
if ( d -> front == NULL )
d -> front = temp ;
else
d -> rear -> next = temp ;
d -> rear = temp ;
return 1;
}
int EnqueueFront(deque *d, element item )
{
struct cell *temp ;
temp = ( struct cell * ) malloc ( sizeof ( struct cell ) );
if(!temp) return 0;
temp -> data = item ;
temp -> next = NULL ;
if ( d -> front == NULL )
d -> front = d -> rear = temp ;
else
{
temp -> next = d -> front ;
d -> front = temp ;
}
return 1;
}
int DeleteFront (deque *d )
{
struct cell *temp ;
if ( isEmptyDeque(*d) ) return 0 ;
temp = d -> front ;
d -> front = temp -> next ;
free ( temp ) ;
if ( temp == NULL )
d -> rear = NULL ;
return 1;
}
int DeleteRear(deque *d)
{
struct cell *p ;
if ( isEmptyDeque(*d) ) return 0 ;
if (d->front == d->rear)
{
free(d->front);
d->front = d->rear = NULL ;
return 1 ;
}
p = d->front ;
while (p->next != d->rear)
p = p->next;
free(d->rear);
p->next = NULL;
d->rear = p;
return 1;
}
int Front(deque d, element *e)
{
if(isEmptyDeque(d)) return 0;
*e=d.front->data;
return 1;
}
int Rear(deque d, element *e)
{
if(isEmptyDeque(d)) return 0;
*e=d.rear->data;
return 1;
}
void display (deque d )
{
struct cell *temp = d.front ;
printf ( "\nfront -> " ) ;
while ( temp != NULL )
{
if ( temp -> next == NULL )
{
printf ( " %d", temp -> data ) ;
printf ( " <- rear" ) ;
}
else
printf ( " %d", temp -> data ) ;
temp = temp -> next ;
}
printf ( "\n" ) ;
}
int main()
{
deque d;
int i;
d=CreateDeque();
for(i=1;i<10;i++)
{
EnqueueFront (&d, i );
EnqueueRear (&d, i );
display(d);
}
for(i=1;i<10;i++)
{
DeleteFront (&d);
DeleteRear (&d);
display(d);
}
return 0;
}
Back to the list of exercises
Looking for a more challenging exercise, try this one !!
Divisibility by 9