Skip to content
Part IA Lent Term

Stacks

Abstract Data Type

A stack is a last-in, first-out (LIFO) collection. The element most recently added (pushed) is the first one removed (popped). Operations:

OperationDescription
PUSH(S, x)Add element xx to the top of the stack
POP(S)Remove and return the top element
TOP(S) / PEEK(S)Return the top element without removing it
IS-EMPTY(S)Return true iff stack contains no elements

Array Implementation

Maintain an array A[1..n] of maximum capacity nn and a variable top that tracks the current top position. Two conventions exist:

Convention 1: top is the index of the current top element (0 means empty).

  • PUSH: top = top + 1; A[top] = x
  • POP: x = A[top]; top = top - 1; return x

Convention 2: top is the index of the first free slot (1 means empty).

  • PUSH: A[top] = x; top = top + 1
  • POP: top = top - 1; return A[top]

All operations are Θ(1)\Theta(1). Overflow occurs when pushing onto a full stack (top=n\texttt{top} = n or top=n+1\texttt{top} = n+1, depending on convention).

Linked List Implementation

Push adds a new node at the head; pop removes the head node. Both are Θ(1)\Theta(1). No capacity limit (until memory exhaustion).

PUSH(S, x):
    node = new Node(value=x, next=S.head)
    S.head = node

POP(S):
    if S.head == NIL: error "empty"
    x = S.head.value
    S.head = S.head.next
    return x

Additional Operations (Challenge)

Design a stack supporting AVERAGE(S) in Θ(1)\Theta(1):

Maintain a running sum total and count size alongside the stack. On push: total += x; size += 1. On pop: total -= popped_value; size -= 1. AVERAGE returns total / size in Θ(1)\Theta(1).

For MIN(S) in Θ(1)\Theta(1), maintain a second stack of minimums: on push, also push min(x,current min)\min(x, \text{current min}) onto the min-stack; on pop, pop both stacks. MIN reads the top of the min-stack.

Applications

ApplicationHow the stack is used
Function call stackReturn addresses and local variables are pushed on call, popped on return
Expression evaluation (postfix/RPN)Push operands; on operator, pop operands, evaluate, push result
Undo functionalityEach action is pushed; undo pops and reverses
Bracket matchingPush opening brackets; on closing bracket, pop and check match
Depth-first searchImplicit via recursion, or explicit with a stack of vertices to visit

Summary

PropertyArrayLinked List
PUSHΘ(1)\Theta(1)Θ(1)\Theta(1)
POPΘ(1)\Theta(1)Θ(1)\Theta(1)
TOPΘ(1)\Theta(1)Θ(1)\Theta(1)
IS-EMPTYΘ(1)\Theta(1)Θ(1)\Theta(1)
Max capacityFixed (nn)Unbounded
SpaceΘ(n)\Theta(n) pre-allocatedProportional to number of elements
PrincipleLIFO