Deque in C: solved exercise
Deque in C: solved exercise
If you searched for a solved deque in C, here is the circular-array implementation that supports O(1) insertion and removal at both ends. A deque (double-ended queue) generalizes both the stack and the queue: it can be used as either.
With a circular array, the front and rear indices advance modulo CAPACITY, avoiding element shifting.
Problem statement
Implement a fixed-capacity deque of 8 elements supporting:
push_front(d, v): insert at the front.push_back(d, v): insert at the back.pop_front(d): remove and return the front element.pop_back(d): remove and return the back element.print(d): display contents from front to back.
Demonstrate all four operations with a sequence of insertions and removals.
C solution
Expected output
Common mistakes
- Not applying the
CAPmodulo when computingfront - 1: in C, the%operator with negative numbers can give a negative result; use(front - 1 + CAP) % CAP. - Confusing the back index with
front + size: the back is at(front + size - 1) % CAP, sincefront + sizepoints to the first empty slot. - Not checking if the deque is full before
push_frontorpush_back: inserting whensize == CAPoverwrites existing elements. - Initializing
frontto a non-zero value: for simplicity,front = 0andsize = 0is the standard initialization.
Practical use
The deque is used in sliding window algorithms (maximum/minimum in a window of size k), task scheduling (insertion and removal at both ends), as the underlying structure of bidirectional BFS, and in simulators of priority queues at both ends.
Recommended next exercise
Guided practice and full book
If you want a complete path with progressive difficulty:
FAQ
What is the difference between a deque and a regular queue?
A queue (FIFO) only allows insertion at the back and removal at the front. A deque allows insertion and removal at both ends. The deque is a superset: it can simulate both a queue (using only push_back and pop_front) and a stack (using only push_back and pop_back).
Why use a circular array instead of a linked list?
A circular array guarantees O(1) for all operations without dynamic memory allocation, making it faster and with better cache locality than a linked list. A linked list is preferable when the capacity is unknown or unlimited.
What is the time complexity of the four deque operations?
All four operations (push_front, push_back, pop_front, pop_back) are O(1) with the circular array. The print operation is O(n) as it traverses all elements.