Dequeue
Dequeue
changes and similar structure to the previous queue code. A Deque allows insertion and
deletion of elements from both ends (front and rear).
---
#include <stdio.h>
#include <stdlib.h>
#define MAX 5
int deque[MAX];
int front = -1, rear = -1;
int isFull() {
return ((rear + 1) % MAX == front);
}
int isEmpty() {
return (front == -1);
}
int deleteFront() {
if (isEmpty()) {
printf("Deque Underflow! No elements to delete from front\n");
return -1;
} else {
int deletedElement = deque[front];
if (front == rear) {
front = rear = -1;
} else {
front = (front + 1) % MAX;
}
return deletedElement;
}
}
int deleteRear() {
if (isEmpty()) {
printf("Deque Underflow! No elements to delete from rear\n");
return -1;
} else {
int deletedElement = deque[rear];
if (front == rear) {
front = rear = -1;
} else {
rear = (rear - 1 + MAX) % MAX;
}
return deletedElement;
}
}
int peekFront() {
if (isEmpty()) {
printf("Deque is empty\n");
return -1;
} else {
return deque[front];
}
}
int peekRear() {
if (isEmpty()) {
printf("Deque is empty\n");
return -1;
} else {
return deque[rear];
}
}
int main() {
insertRear(10);
insertRear(20);
insertFront(30);
insertFront(40);
printf("Front element is %d\n", peekFront());
printf("Rear element is %d\n", peekRear());
deleteFront();
printf("Front element is %d\n", peekFront());
deleteRear();
printf("Rear element is %d\n", peekRear());
return 0;
}
---
The function inserts an element at the front of the queue, adjusting the front pointer. If the
deque is full, it prints an error message.
The function inserts an element at the rear of the queue, adjusting the rear pointer. If the
deque is full, it prints an error message.
The function removes the element from the front of the deque, adjusting the front pointer. If
the deque is empty, it prints an error message.
The function removes the element from the rear of the deque, adjusting the rear pointer. If
the deque is empty, it prints an error message.
5. Peek Front (peekFront):
The function returns the front element without removing it. If the deque is empty, it returns -1.
The function returns the rear element without removing it. If the deque is empty, it returns -1.
---
Flexibility: Deques allow elements to be inserted and removed from both ends, unlike
queues that allow only from the front and rear.
Circular Structure: The queue is circular, using modulo (% MAX) to wrap the front and rear
pointers around the array.
Overflow and Underflow: The deque is full if the next position (after adjusting for the circular
nature) of rear equals front, and underflow occurs when the deque is empty.
---