Sub topic 7
Stacks: LIFO, Push, Pop, and Overflow/Underflow
Assume you know loops, functions, object references, and introductory Big-O notation. A stack is a linear abstract data type (ADT) in which insertion and removal happen at one end, called the top. Its rule is LIFO, or “last in, first out.” The newest item leaves first, like the top plate in a pile.
Core operations
- push(x) adds
xto the top. - pop() removes and returns the top item.
- peek() returns the top item without removing it.
- is_empty() checks whether the stack has no items.
For a stack with fixed capacity, pushing into a full stack causes overflow. Popping or peeking from an empty stack causes underflow.
| Operation | Array stack | Linked-list stack |
|---|---|---|
| push | O(1), unless resizing | O(1) |
| pop | O(1) | O(1) |
| peek | O(1) | O(1) |
| extra space | O(n) | O(n), including links |
Array implementation
An array stack stores items from index 0 through top. The value top = -1 represents an empty stack. With capacity C, the stack is full when top = C - 1.
class ArrayStack:
def __init__(self, capacity):
self.items = [None] * capacity
self.top = -1
def push(self, value):
if self.top == len(self.items) - 1:
raise OverflowError("stack overflow")
self.top += 1
self.items[self.top] = value
def pop(self):
if self.top == -1:
raise IndexError("stack underflow")
value = self.items[self.top]
self.items[self.top] = None
self.top -= 1
return value
def peek(self):
if self.top == -1:
raise IndexError("stack underflow")
return self.items[self.top]After push(4), push(7), and push(9), the top item is 9. The calls pop(), pop(), and pop() return 9, 7, and 4.
Linked-list implementation
A linked-list stack keeps the top pointer at the first node. Each push creates a node before the old top. Each pop removes the first node. No shifting is needed.
Trace the LIFO rule
A stack is useful for nested function calls, undo operations, depth-first search, and expression processing. In each case, the most recently pending item must be handled first.
Exercise
A stack has capacity 3 and starts empty. What happens after push(2), push(5), pop(), push(8), push(1)?
Show answer
pop() returns 5. The remaining values are 2 and 8, then push(1) succeeds, leaving 1 at the top. The stack is full with bottom-to-top order 2, 8, 1.