Sub topic 2
Stacks: LIFO, push, pop, and overflow/underflow
This chapter assumes you know arrays, pointers or object references, and Big-O notation.
Stacks: LIFO, push, pop, and overflow/underflow
A stack is a list that accesses only one end, the top. It follows LIFO (last in, first out). push adds an item to the top, and pop removes it. Both run in O(1) time.
An array-based stack with capacity n overflows when push runs on a full stack. It underflows when pop runs on an empty stack. Check for both before each operation.
Stack applications: balanced parentheses, infix to postfix, postfix evaluation
To check balanced parentheses, push each opener. Each closer must match the most recent unmatched opener.
def is_balanced(s):
pairs = {')': '(', ']': '[', '}': '{'}
stack = []
for ch in s:
if ch in '([{':
stack.append(ch)
elif ch in pairs:
if not stack or stack.pop() != pairs[ch]:
return False
return not stackTo convert infix to postfix, copy operands to the output. Before pushing an operator, pop operators of equal or higher precedence (for left-associative operators). For A + B * C, the output is A B C * +, because * outranks +.
To evaluate postfix, push operands. When you reach an operator, pop two values, apply the operator, and push the result. For 2 3 4 * +, the stack goes 2, 3, 4, then 12, then 14.
Queues: FIFO, enqueue, dequeue, and pointer handling
A queue follows FIFO (first in, first out). enqueue adds at the rear, and dequeue removes at the front. In a linked list, keep both front and rear pointers so each operation runs in O(1). When the last node leaves, set rear to NULL. Otherwise, a later enqueue writes through a dangling pointer.
Circular queues: wrap-around and full/empty conditions
A linear array queue wastes space after dequeues. A circular queue wraps indices with modulo arithmetic. Store front and size. The k-th element sits at (front + k) % n. The queue is full when size == n and empty when size == 0. Keeping a count avoids wasting a slot.
Deques and restricted queues
A deque (double-ended queue) inserts and deletes at both ends. An input-restricted deque allows insertion at only one end. An output-restricted deque allows deletion at only one end.
Building a stack from queues and a queue from stacks
To build a stack with one queue, enqueue the new item, then rotate the other n-1 items to the back. push costs O(n), and pop is a single dequeue.
To build a queue with two stacks, push new items onto in. For dequeue, if out is empty, pop all of in onto out, then pop out. Each item moves at most twice, so the amortized cost is O(1).
Exercise
Evaluate the postfix expression 5 1 2 + 4 * + 3 -.
Show answer
14. The stack goes 5, 1, 2, then 5, 3 after the first +, then 5, 3, 4, then 5, 12 after *, then 17 after the second +, then 17, 3, then 14 after -.