0% found this document useful (0 votes)
6 views4 pages

Dequeue

The document describes the implementation of a Double Ended Queue (Deque) in C, allowing insertion and deletion from both ends. It includes functions for inserting and deleting elements at the front and rear, as well as displaying the current elements in the deque. The main function provides an example of how to use these operations.

Uploaded by

sidehustle0307
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views4 pages

Dequeue

The document describes the implementation of a Double Ended Queue (Deque) in C, allowing insertion and deletion from both ends. It includes functions for inserting and deleting elements at the front and rear, as well as displaying the current elements in the deque. The main function provides an example of how to use these operations.

Uploaded by

sidehustle0307
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Deque

A Double Ended Queue (Deque) allows insertion and deletion from both front and
rear.
Global Declarations
#include <stdio.h>
#define MAX 5

int deque[MAX];
int front = -1;
int rear = -1;

1. Insert at Front
void insertFront(int x) {
if ((front == 0 && rear == MAX - 1) || (front == rear + 1)) {
printf("Deque Overflow\n");
return;
}

if (front == -1) { // first element


front = rear = 0;
} else if (front == 0) {
front = MAX - 1;
} else {
front--;
}

deque[front] = x;
}

2. Insert at Rear
void insertRear(int x) {
if ((front == 0 && rear == MAX - 1) || (front == rear + 1)) {
printf("Deque Overflow\n");
return;
}

if (front == -1) {
front = rear = 0;
} else if (rear == MAX - 1) {
rear = 0;
} else {
rear++;
}

deque[rear] = x;
}

3. Delete from Front


void deleteFront() {
if (front == -1) {
printf("Deque Underflow\n");
return;
}

printf("Deleted element: %d\n", deque[front]);

if (front == rear) {
front = rear = -1;
} else if (front == MAX - 1) {
front = 0;
} else {
front++;
}
}

4. Delete from Rear


void deleteRear() {
if (front == -1) {
printf("Deque Underflow\n");
return;
}

printf("Deleted element: %d\n", deque[rear]);

if (front == rear) {
front = rear = -1;
} else if (rear == 0) {
rear = MAX - 1;
} else {
rear--;
}
}

5. Display Deque
void display() {
if (front == -1) {
printf("Deque is empty\n");
return;
}

int i = front;
printf("Deque elements: ");

while (1) {
printf("%d ", deque[i]);
if (i == rear)
break;
i = (i + 1) % MAX;
}
printf("\n");
}

6. Main Function (Example)


int main() {
insertRear(10);
insertRear(20);
insertFront(5);
insertFront(2);

display();

deleteFront();
deleteRear();

display();

return 0;
}

You might also like