Sub topic 7
Stacks: LIFO, push, pop, and overflow/underflow
This chapter assumes you can write loops and functions in C, Java, or Python. It also assumes you know what a pointer or object reference is, and that you have read the earlier chapters on arrays and singly linked lists.
The stack as an abstract data type
A stack is a collection that allows insertion and removal at only one end, called the top. The element inserted most recently is the first one removed. This rule is called LIFO (last in, first out).
The core operations are:
push(x)placesxon top of the stack.pop()removes the top element and returns it.peek()(also calledtop()) returns the top element without removing it.is_empty()reports whether the stack holds no elements.is_full()reports whether a fixed-capacity stack has no room left. A linked stack has no such check.
An abstract data type (ADT) defines these operations and their meaning, not how they are stored. Both an array and a linked list can implement the same stack ADT. The difference between them is cost, not behaviour.
Two error conditions matter in every implementation:
- Overflow is a
pushon a full stack. It can only happen with a fixed-capacity array, or when memory runs out. - Underflow is a
poporpeekon an empty stack.
Array implementation
An array stack keeps a fixed-size array and an integer top. The usual convention is that top holds the index of the top element, so an empty stack has top = -1.
With capacity n:
- The stack is empty when
top == -1. - The stack is full when
top == n - 1. - The stack holds
top + 1elements.
class ArrayStack:
def __init__(self, capacity):
self.a = [None] * capacity
self.top = -1
def push(self, x):
if self.top == len(self.a) - 1:
raise OverflowError('stack overflow')
self.top += 1
self.a[self.top] = x
def pop(self):
if self.top == -1:
raise IndexError('stack underflow')
x = self.a[self.top]
self.a[self.top] = None
self.top -= 1
return x
def peek(self):
if self.top == -1:
raise IndexError('stack underflow')
return self.a[self.top]
s = ArrayStack(3)
s.push(10)
s.push(20)
print(s.pop(), s.peek())This prints 20 10. Every operation does a constant amount of work, so push, pop, and peek are all O(1).
Exam questions sometimes initialise top = 0 instead, meaning top points to the next free slot. Then empty is top == 0 and full is top == n. The conditions follow from the convention in the question. Read the convention before you answer.
Linked list implementation
A linked stack uses a singly linked list. The head of the list is the top of the stack. Push inserts a new node at the head, and pop removes the head. Both are O(1). Insertion and deletion at the tail would need O(n) traversal in a singly linked list, so the head is the right end to use.
class Node:
def __init__(self, data, next=None):
self.data = data
self.next = next
class LinkedStack:
def __init__(self):
self.head = None
def push(self, x):
self.head = Node(x, self.head)
def pop(self):
if self.head is None:
raise IndexError('stack underflow')
x = self.head.data
self.head = self.head.next
return x
def is_empty(self):
return self.head is None
s = LinkedStack()
for v in (1, 2, 3):
s.push(v)
print(s.pop(), s.pop(), s.pop())This prints 3 2 1. The stack is never full while memory remains, so overflow does not occur in the logical sense. It would happen only if the system cannot allocate a node. Underflow still occurs on an empty list.
Comparing the two implementations
| Aspect | Array stack | Linked stack |
|---|---|---|
| push, pop, peek | O(1) | O(1) |
| Overflow | Possible at a fixed capacity | Only if memory is exhausted |
| Extra memory per element | None | One pointer per node |
| Memory layout | Contiguous, cache friendly | Scattered nodes |
| Unused space | Unused slots up to capacity | None |
| Allocation cost per push | None (preallocated) | One node allocation |
A dynamic array (such as a Python list or a C++ vector) removes the fixed-capacity limit. It doubles its size when full. A single push can then cost O(n) because of the copy, but the amortized cost over many pushes is still O(1).
Stack sequences: which pop orders are possible
A common GATE pattern pushes elements in a fixed order, with pops allowed at any time, and asks which output sequences are possible.
Take the input order 1, 2, 3, 4 and ask whether the output 3 1 2 4 is possible. Trace it:
- To output 3 first, push 1, 2, 3, then pop 3. The stack holds 1, 2 with 2 on top.
- The next output is 1, but 2 is above 1. Popping would give 2, not 1, so the sequence is impossible.
A quick test for a permutation of 1..n pushed in order: no output may contain three values a < b < c appearing in the order c, a, b. Here 3, 1, 2 is exactly that pattern. The number of valid output permutations of n distinct elements is the Catalan number C(n) = (2n)! / ((n+1)! n!). That gives 5 for n = 3 and 14 for n = 4.
Counting operations and stack height
Questions often give a mixed sequence of pushes and pops and ask for the final size or the first error. Count carefully:
- Each successful push raises the size by 1, and each successful pop lowers it by 1.
- Underflow occurs at the first point where a pop is applied to size 0.
- For a stack of capacity
n, overflow occurs at the first push applied to sizen.
For example, take capacity 3 and the sequence push, push, pop, push, push, push. The sizes after each step are 1, 2, 1, 2, 3, then the last push is applied to size 3 and overflows.
Two stacks in one array
To use one array of size n for two stacks, start one stack at index 0 growing upward and the other at index n - 1 growing downward. With top1 starting at -1 and top2 starting at n:
- Stack 1 is empty when
top1 == -1. - Stack 2 is empty when
top2 == n. - The array is full, and either push overflows, when
top1 + 1 == top2.
The two stacks share the free space, so neither overflows while any slot is free. Splitting the array into two halves wastes space because one half can fill while the other is nearly empty.
Common mistakes
- Reading
top = 0as the empty condition without checking the question's convention. - Popping before testing for underflow, or pushing before testing for overflow, so the index goes out of bounds.
- In a linked stack, moving the head before saving the old data, which loses the value you meant to return.
- Using the tail as the top of a singly linked stack, which turns pop into O(n).
- Assuming a linked stack can never fail. It can fail on memory allocation.
Exercise
A stack is implemented as an array of size 5 with top initialised to -1. Starting from empty, the operations push, push, push, pop, pop, pop, pop, push run in order. Which operation causes an error, what kind of error is it, and what is top after the final operation if the erroring operation is skipped?
Show answer
Sizes after each step are 1, 2, 3, 2, 1, 0. The fourth pop (the seventh operation) is applied to size 0, so it causes underflow. Skipping it, the final push brings the size to 1, so top = 0.
Exercise
Elements 1, 2, 3, 4 are pushed in this order, with pops interleaved at any point. Is the output 4 2 3 1 possible? How many different output sequences are possible in total?
Show answer
No. To output 4 first you must push 1, 2, 3, 4 and pop 4, leaving 3 on top of 2. The next output 2 would require popping 3 first, so 4 2 3 1 is impossible. The total number of valid outputs is the Catalan number C(4) = 14.