CIE AS & A Level Computer Science, section 19.1 (Algorithms)
Stack (last in, first out)
A stack is an ADT where the last item added is the first removed. Operations: push (add), pop (remove and return), peek, and checks for empty and full. A top pointer shows the position of the top item.
class Stack:
def __init__(self, size):
self.data = [None] * size
self.top = -1 # -1 means empty
def push(self, item):
if self.top == len(self.data) - 1:
raise OverflowError("stack full")
self.top += 1
self.data[self.top] = item
def pop(self):
if self.top == -1:
raise IndexError("stack empty")
item = self.data[self.top]
self.top -= 1
return item
s = Stack(5)
s.push(10); s.push(20); s.push(30)
print(s.pop(), s.pop()) # 30 20
Uses: undo, backtracking, and the call stack for procedures and recursion.
Queue (first in, first out)
A queue removes items in the order they were added. Operations: enqueue (add at the rear) and dequeue (remove from the front). Pointers: front and rear.
A circular queue reuses the freed space at the start of the array: the pointers wrap round using MOD.
class CircularQueue:
def __init__(self, size):
self.data = [None] * size
self.front = 0
self.count = 0
def enqueue(self, item):
if self.count == len(self.data):
raise OverflowError("queue full")
rear = (self.front + self.count) % len(self.data)
self.data[rear] = item
self.count += 1
def dequeue(self):
if self.count == 0:
raise IndexError("queue empty")
item = self.data[self.front]
self.front = (self.front + 1) % len(self.data)
self.count -= 1
return item
q = CircularQueue(3)
q.enqueue("A"); q.enqueue("B"); q.enqueue("C")
print(q.dequeue()) # A
q.enqueue("D") # reuses the freed space
print(q.dequeue(), q.dequeue(), q.dequeue()) # B C D
Uses: printer queues, keyboard buffers and scheduling.
Comparing
| Stack | Queue | |
|---|---|---|
| Order | LIFO | FIFO |
| Add at | top | rear |
| Remove from | top | front |
Common mistake: checking for empty and full wrongly: an operation must test the condition before it changes a pointer. Also, in a circular queue, forgetting to use MOD makes the pointer run off the end of the array.
Exam tip: in a trace, draw the array and show the pointer values after each operation. State the order of removal as LIFO or FIFO.
Check yourself
Which ADT removes the item that was added most recently?
A stack (last in, first out).
Why is a circular queue better than a linear queue in an array?
The space freed at the front can be reused, as the pointers wrap round.
Give one use of a stack.
The call stack for procedure calls, or an undo feature.