C Deque (Double-Ended Queue) 🎯

beginner
17 min

C Deque (Double-Ended Queue) 🎯

Welcome to our in-depth guide on C Deque! In this lesson, we'll explore the Double-Ended Queue data structure and understand how to implement it using C programming. By the end of this tutorial, you'll have a solid grasp of Deques and be able to apply this knowledge to your own projects. 📝

What is a Deque? 💡

A Deque, short for Double-Ended Queue, is a flexible linear data structure that allows adding and removing elements from both ends. This makes Deques very useful in various real-world applications, such as maintaining a history of browser navigation or implementing a priority queue.

C Deque: Basic Implementation 💡

To create a Deque in C, we'll use an array along with two pointers - front and rear - to keep track of the elements. Here's a simple Deque implementation:

c
#include <stdio.h> #include <stdlib.h> #define MAX 10 typedef struct Deque { int arr[MAX]; int front, rear; } Deque; void initialize(Deque *d) { d->front = d->rear = -1; } int isEmpty(Deque *d) { return (d->front == -1); } void addFront(Deque *d, int x) { 📝 If the Deque is full, handle the situation appropriately. if ((d->rear + 1) % MAX == d->front) { printf("Error: Deque overflow.\n"); return; } if (isEmpty(d)) d->front = 0; d->arr[d->front] = x; d->front = (d->front - 1 + MAX) % MAX; } void addRear(Deque *d, int x) { 📝 If the Deque is full, handle the situation appropriately. if ((d->rear + 1) % MAX == d->front) { printf("Error: Deque overflow.\n"); return; } d->rear = (d->rear + 1) % MAX; d->arr[d->rear] = x; } int removeFront(Deque *d) { 📝 Handle the situation if the Deque is empty. if (isEmpty(d)) { printf("Error: Deque underflow.\n"); return -1; } int x = d->arr[d->front]; d->front = (d->front + 1) % MAX; return x; } int removeRear(Deque *d) { 📝 Handle the situation if the Deque is empty. if (isEmpty(d)) { printf("Error: Deque underflow.\n"); return -1; } int x = d->arr[d->rear]; if (--d->rear == d->front) initialize(d); return x; } void printDeque(Deque d) { if (isEmpty(d)) { printf("Deque is empty.\n"); return; } printf("Deque: "); int i = (d.front + 1) % MAX; do { printf("%d ", d.arr[i]); i = (i + 1) % MAX; } while (i != d.rear); printf("\n"); } int main() { Deque d; initialize(&d); addRear(&d, 1); addRear(&d, 2); addRear(&d, 3); addFront(&d, 4); addFront(&d, 5); printDeque(d); removeFront(&d); removeRear(&d); printf("After removing elements: "); printDeque(d); return 0; }

Quiz 💡

Quick Quiz
Question 1 of 1

What data structure does the provided C code implement?

C Deque: Advanced Applications 💡

In addition to basic operations, you can further extend the C Deque implementation for more advanced applications like implementing a circular buffer or a priority queue.

That's all for today! We hope you enjoyed learning about C Deques and gained a better understanding of this powerful data structure. Happy coding! 🎯