Published by Patrick Mutisya · 14 days ago
Describe how a queue, stack and linked list can be implemented using arrays.
Arrays provide contiguous memory, constant‑time access by index and a fixed maximum size. By managing additional variables (such as front, rear, top, or next‑index), we can give the array the behaviour of higher‑level abstract data types.
A stack can be realised with a one‑dimensional array stack[0 … N‑1] and an integer top that points to the most recently inserted element.
top = -1 (empty stack).top == N‑1 (stack full). If so, raise overflow.top.stack[top] = value.top == -1 (stack empty). If so, raise underflow.value = stack[top].top.value.stack[top] without modifying top.top pointer.
A queue can be built from an array queue[0 … N‑1] using two indices: front (position of the first element) and rear (position where the next element will be inserted). To avoid moving elements, a circular buffer is used.
front = 0, rear = 0, size = 0.size == N, the queue is full – raise overflow.queue[rear] = value.rear = (rear + 1) mod N.size.size == 0, the queue is empty – raise underflow.value = queue[front].front = (front + 1) mod N.size.value.queue[front] without changing indices.front and rear pointers.
A linked list can be simulated with two parallel arrays:
data[0 … N‑1] – stores the actual element values.next[0 … N‑1] – stores the index of the next node (or –1 for null).A separate variable head holds the index of the first node, and a free list (often a stack of unused indices) manages allocation.
for i = 0 to N‑1:
next[i] = i+1 // link all cells into a free list
next[N‑1] = -1
head = -1 // empty list
free = 0 // first free cell
free == -1, the array is full – raise overflow.new = free.free = next[free] (remove from free list).data[new] = value.next[new] = head.head = new.head == -1, the list is empty – raise underflow.del = head.head = next[head].next[del] = free
free = del
head and free pointers.
| ADT | Operation | Array Implementation | Time Complexity |
|---|---|---|---|
| Stack | Push | Increment top and store value | \$O(1)\$ |
| Pop | Return stack[top] then decrement top | \$O(1)\$ | |
| Peek | Read stack[top] | \$O(1)\$ | |
| Queue | Enqueue | Store at rear, advance circularly | \$O(1)\$ |
| Dequeue | Read at front, advance circularly | \$O(1)\$ | |
| Peek | Read queue[front] | \$O(1)\$ | |
| Size | Maintain a size counter | \$O(1)\$ | |
| Static Linked List | Insert at head | Allocate from free list, adjust next pointers | \$O(1)\$ |
| Delete at head | Adjust head, return node to free list | \$O(1)\$ | |
| Search (by value) | Traverse next chain | \$O(n)\$ |