A deque (double-ended queue) allows insertion and removal at both ends: push_front, push_back, pop_front, pop_back. It generalizes both stacks and queues. A circular array handles it neatly: pushing at the front moves head backward with modulo.
Remember
push_back : data[(head + count) % CAP] = v;
push_front: head = (head + CAP - 1) % CAP; data[head] = v;
pop_front : v = data[head]; head = (head + 1) % CAP;
pop_back : v = data[(head + count - 1) % CAP];
Reference
Cheat Sheet
Keep these facts handy while you work with Deque (Double-Ended Queue) in C in C.
Topic
Detail
Stack mode
Use one end only
Queue mode
push_back + pop_front
All ops
O(1)
Move head back
+ CAP before %
Code
C Examples
Compile each example with gcc file.c -std=c11 -Wall -o out. Next: Priority Queue.
Example 1 — A deque of four slots
Push at both ends and pop at both ends.
C
#include <stdio.h>
#define CAP 4
struct Deque { int data[CAP]; int head, count; };
static void push_back(struct Deque *d, int v) {
d->data[(d->head + d->count) % CAP] = v;
d->count++;
}
static void push_front(struct Deque *d, int v) {
d->head = (d->head + CAP - 1) % CAP;
d->data[d->head] = v;
d->count++;
}
static int pop_front(struct Deque *d) {
int v = d->data[d->head];
d->head = (d->head + 1) % CAP;
d->count--;
return v;
}
static int pop_back(struct Deque *d) {
int v = d->data[(d->head + d->count - 1) % CAP];
d->count--;
return v;
}
static void show(const struct Deque *d) {
printf("deque:");
for (int i = 0; i < d->count; i++) printf(" %d", d->data[(d->head + i) % CAP]);
printf("\n");
}
int main(void) {
struct Deque d = {{0}, 0, 0};
push_back(&d, 2); push_back(&d, 3);
push_front(&d, 1); push_front(&d, 0);
show(&d);
printf("pop_back: %d\n", pop_back(&d));
printf("pop_front: %d\n", pop_front(&d));
show(&d);
return 0;
}