Lecture 4: Stack

One-line version

A stack is a list where you can only touch one end, the top. push adds there and pop removes from there, so the last item in is the first one out (LIFO). You can build it on a dynamic array (top is an index) or on a linked list (top is the head pointer). Either way every operation is O(1).

Previous: Lecture 3 - Linked List · Next: Lecture 5 - Queue

Where the material comes from

Sections 1 to 6 and 8 follow the slides. Section 7 (decimal to hex, infix to postfix) is marked self-study in the slides, so the code there is ours. Section 9 comes from the course practice sheet (questions 16 to 20). The slides show the class declarations but not the full .cpp files; the member function bodies in sections 4 and 5 are written to match those declarations.


1. What is a stack?

  • A simple container holding a linear list of elements.
  • Access is by position, meaning order of insertion. There is no searching and no indexing.
  • All insertions and deletions happen at one end, called the top.
  • So it is Last In, First Out (LIFO): the last item pushed is the first item popped.

Two basic operations:

Operation Effect top
push(x) add x on top moves up
pop() remove the top item moves down
flowchart LR
    subgraph before["start"]
        direction TB
        a30["30 ← top"] --- a20["20"] --- a10["10"]
    end
    subgraph pushed["after push(40)"]
        direction TB
        b40["40 ← top"] --- b30["30"] --- b20["20"] --- b10["10"]
    end
    subgraph popped["after pop()"]
        direction TB
        c30["30 ← top"] --- c20["20"] --- c10["10"]
    end
    before --> pushed --> popped
Picture a pile of plates

You put a plate on top and you take the top plate off. To reach the bottom plate you must remove every plate above it first.


2. Where stacks are used

Use What the stack holds
Run-time stack for function calls one frame (locals, return address) per active call
Web browser “back” history the pages you visited, most recent on top
Undo in a text editor the edits, most recent on top
Removing recursion the work a recursive call would have saved
Infix to postfix conversion operators waiting for their second operand
Postfix evaluation operands and partial results
Reversing a sequence push everything, then pop: it comes out reversed
Balanced symbols the opening brackets not closed yet

Every row has the same shape: the thing you need next is the thing you saw most recently.


3. The Stack ADT

Operation Meaning
construct create an empty stack
stackIsEmpty() → bool true if the stack is empty
stackIsFull() → bool true if the stack is full (array version only)
push(el) add el at the top
pop(el) retrieve and remove the top element, into el
stackTop(el) retrieve the top element without removing it (often called peek)
pop and stackTop return through a reference

In the slides’ ADT, pop(Type &) and stackTop(Type &) hand the value back through a reference parameter, not as a return value. The caller writes s.pop(x); and then uses x. Only pop changes the stack.

Overflow and underflow
  • Overflow: push on a full stack. Only an array stack can be full.
  • Underflow: pop or stackTop on an empty stack. Either version can be empty.

Check stackIsFull() before pushing and stackIsEmpty() before popping.


4. Array-based stack (Stackt)

  • The stack is a dynamic array allocated in the constructor.
  • The capacity MaxSize is a constructor parameter, default 128.
  • It is a template class so the element type is chosen by the user (Stackt<int>, Stackt<char>, …).
  • top is the index of the top element, and -1 means empty.

Declaration (Stackt.h, from the slides)

// File: Stackt.h
// Stack template class definition. Dynamic array implementation
#ifndef STACKT_H
#define STACKT_H

template <class Type>
class Stackt {
public:
    Stackt(int nelements = 128);        // Constructor
    Stackt(const Stackt<Type>&);        // Copy Constructor
    ~Stackt();                          // Destructor

    void push(Type);                    // Push
    void pop(Type&);                    // Pop
    void stackTop(Type&) const;         // retrieve top
    bool stackIsEmpty() const;          // Test for Empty stack
    bool stackIsFull() const;           // Test for Full stack
private:
    Type* stack;                        // pointer to dynamic array
    int top, MaxSize;
};

#endif // STACKT_H
#include "Stackt.cpp"

Because it is a template, the implementation file is #included at the bottom of the header, the same trick as the List class in Lecture 3 - Linked List.

Implementation (Stackt.cpp)

template <class Type>
Stackt<Type>::Stackt(int nelements) {     // default value only in the .h
    MaxSize = nelements;
    stack = new Type[MaxSize];
    top = -1;                             // empty
}

template <class Type>
Stackt<Type>::Stackt(const Stackt<Type>& original) {
    MaxSize = original.MaxSize;
    top = original.top;
    stack = new Type[MaxSize];            // our OWN array
    for (int i = 0; i <= top; i++)
        stack[i] = original.stack[i];
}

template <class Type>
Stackt<Type>::~Stackt() {
    delete[] stack;
}

template <class Type>
void Stackt<Type>::push(Type v) {
    if (stackIsFull()) {
        std::cout << "Stack Overflow\n";
        return;                           // do NOT write past the end
    }
    stack[++top] = v;                     // move up, then store
}

template <class Type>
void Stackt<Type>::pop(Type& v) {
    if (stackIsEmpty()) {
        std::cout << "Stack Underflow\n";
        return;
    }
    v = stack[top--];                     // read, then move down
}

template <class Type>
void Stackt<Type>::stackTop(Type& v) const {
    if (!stackIsEmpty())
        v = stack[top];                   // read only, top unchanged
}

template <class Type>
bool Stackt<Type>::stackIsEmpty() const { return top < 0; }

template <class Type>
bool Stackt<Type>::stackIsFull() const { return top >= MaxSize - 1; }
flowchart LR
    subgraph arr["stack[] with MaxSize = 5, after push 10, 20, 30"]
        direction LR
        i0["[0] 10"] --- i1["[1] 20"] --- i2["[2] 30"] --- i3["[3] ?"] --- i4["[4] ?"]
    end
    t["top = 2"] -.-> i2
++top vs top--

stack[++top] = v increments first, so it writes into the next free slot. v = stack[top--] reads first, then decrements. Swap them and you overwrite the top or read garbage. Popping doesn’t erase the old value; the slot is just considered free and the next push overwrites it.

Why the copy constructor matters

The class owns a heap array through Type* stack. Without our own copy constructor, C++ copies the members one by one, so the copy’s stack points at the same array:

Stackt<int> a;
a.push(1);
Stackt<int> b = a;   // default copy: b.stack == a.stack
b.push(2);           // also changes a's array
// end of scope: both destructors delete[] the same array → crash

The slides’ copy constructor allocates a new array and copies the elements (a deep copy), so the two stacks are independent. This is needed for any class that owns heap memory, including passing a stack by value to a function.

The slides’ second array version

The slides also show a GeeksforGeeks-style array stack, with different names (Stack, isEmpty, isFull, a fixed SIZE, array st):

template <class T> Stack<T>::Stack() { top = -1; }

template <class T> void Stack<T>::push(T k) {
    if (isFull()) {
        cout << "Stack is full\n";
    }
    cout << "Inserted element " << k << endl;
    top = top + 1;
    st[top] = k;
}

template <class T> bool Stack<T>::isEmpty() { return top == -1; }
template <class T> bool Stack<T>::isFull()  { return top == (SIZE - 1); }
Bug in that push

When the stack is full it prints the message but keeps going: top becomes SIZE and st[SIZE] is written past the end of the array. The fix is to return; inside the if (or put the rest in an else), as in Stackt::push above. Expect “find the bug” questions like this.

Its usage example also calls integer_stack.pop() and prints the result, so in that version pop() returns the value instead of filling a reference. Same idea, different signature:

Stack<int> integer_stack;
integer_stack.push(2);
integer_stack.push(54);
integer_stack.push(255);
cout << integer_stack.pop() << " is removed from stack" << endl;   // 255

5. Linked stack (StackL)

  • A stack can be a linked structure instead of an array.
  • It needs more space (a next pointer per element) but is flexible in size: it is never full until the heap runs out.
  • It is easy because all operations are at one end, and the cheapest end of a singly linked list is the head. So top is the head pointer.
flowchart LR
    top["top"] --> n3["3"] --> n2["2"] --> n1["1"] --> nil["nullptr"]

Declaration (StackL.h, from the slides)

// File: StackL.h
// Linked List Stack class definition
#ifndef STACKL_H
#define STACKL_H

template <class Type>
class StackL {
public:
    StackL();                       // Constructor
    ~StackL();                      // Destructor
    void push(Type);                // Push
    void pop(Type&);                // Pop
    void stackTop(Type&) const;     // retrieve top
    bool stackIsEmpty() const;      // Test for Empty stack
private:
    class node {                    // Hidden from user
    public:
        Type e;                     // stack element
        node* next;                 // pointer to next node
    };
    typedef node* NodePointer;
    NodePointer top;                // pointer to top
};

#endif // STACKL_H
#include "StackL.cpp"

There is no stackIsFull(): a linked stack has no fixed capacity.

Push: insert at the head

NodePointer pnew = new node;
pnew->e = v;
pnew->next = top;    // 1. new node points at the old top
top = pnew;          // 2. top moves to the new node
flowchart LR
    top["top"] --> p["v (new)"] --> n3["3"] --> n2["2"] --> nil["nullptr"]

This is exactly “insert at head” from Lecture 3 - Linked List, with the same rule: link the new node first, then move top. It works on an empty stack too (top is nullptr, so the new node’s next is nullptr).

Pop: delete the head

v = top->e;          // 1. save the top element
cursor = top;        // 2. remember the old top node
top = top->next;     // 3. advance top
delete cursor;       // 4. free the old node

Save the value before delete, and move top before delete (after it you can’t read ->next).

Implementation (StackL.cpp)

template <class Type>
StackL<Type>::StackL() { top = nullptr; }

template <class Type>
StackL<Type>::~StackL() {
    Type junk;
    while (!stackIsEmpty())
        pop(junk);                  // free every node
}

template <class Type>
void StackL<Type>::push(Type v) {
    NodePointer pnew = new node;
    pnew->e = v;
    pnew->next = top;
    top = pnew;
}

template <class Type>
void StackL<Type>::pop(Type& v) {
    if (stackIsEmpty()) {
        std::cout << "Stack Underflow\n";
        return;
    }
    NodePointer cursor = top;
    v = top->e;
    top = top->next;
    delete cursor;
}

template <class Type>
void StackL<Type>::stackTop(Type& v) const {
    if (!stackIsEmpty())
        v = top->e;
}

template <class Type>
bool StackL<Type>::stackIsEmpty() const { return top == nullptr; }

Array vs linked

Array (Stackt) Linked (StackL)
top is an index (-1 = empty) a pointer to the head node (nullptr = empty)
Can be full? yes, at MaxSize no (only if new fails)
Extra space unused slots up to MaxSize one next pointer per element
push / pop O(1) O(1), plus a new / delete
Destructor delete[] stack; pop (or delete) every node
Why not push at the tail of a linked list?

Pushing at the tail is fine with a tail pointer, but popping from the tail needs the node before the tail, which a singly linked list can only find by walking from the head (O(n)). Using the head keeps both operations O(1).


6. Application: balanced symbols

Given a text, check that ( ), [ ] and { } are balanced: every closer matches the most recent unmatched opener.

bool EnclosureBalance(filename) {
    open the file;
    initialize an empty stack of characters;
    balanced = true;
    for each character ch until end of file:
        if ch is a left symbol:  push ch;
        else if ch is a right symbol:
            if the stack is empty:  balanced = false;
            else:
                pop the stack;
                if the popped symbol is not the matching left symbol:
                    balanced = false;
    at the end of the file:
        if the stack is not empty:  balanced = false;
    return balanced;
}

The three ways to fail:

Failure Example Detected when
closer with nothing open a + b) a right symbol meets an empty stack
wrong kind of closer ( ] the popped opener doesn’t match
opener never closed ((a) the stack is not empty at the end

In C++ with a string instead of a file:

bool balanced(const std::string& text) {
    Stackt<char> s;
    char top;
    for (char ch : text) {
        if (ch == '(' || ch == '[' || ch == '{') {
            s.push(ch);
        } else if (ch == ')' || ch == ']' || ch == '}') {
            if (s.stackIsEmpty()) return false;
            s.pop(top);
            if ((ch == ')' && top != '(') ||
                (ch == ']' && top != '[') ||
                (ch == '}' && top != '{')) return false;
        }                       // other characters are ignored
    }
    return s.stackIsEmpty();    // leftover openers = unbalanced
}

Worked example (slides)

{ [ ( a + b ) * ( c - d ) ] }

Symbol Action Stack (bottom → top)
{ push {
[ push { [
( push { [ (
) pop (, matches { [
( push { [ (
) pop (, matches { [
] pop [, matches {
} pop {, matches empty

Empty at the end, so it is balanced. If the final } were ], the popped opener would be {, which doesn’t match ], so it is unbalanced.


7. Application: postfix expressions

Infix vs postfix

  • Infix: the operator sits between its operands, e.g. (A+B) * (C-(D+E)). Parentheses force precedence.
  • Postfix (Reverse Polish Notation, RPN): the operator comes after its operands, and no parentheses are needed. The expression above is A B + C D E + - *.
  • A B + means A + B.

Evaluating postfix

The idea: scan left to right until you hit an operator, apply it to the two previous operands, and replace those operands with the result. The “two previous operands” are always the most recent ones, so a stack holds them.

initialize a stack S
for each token, left to right:
    if it is an operand:  push it on S
    if it is an operator:
        pop two values (error if there aren't two)
        apply the operator
        push the result back on S
at the end, the result is on top of S
    (it must be the ONLY value, otherwise error)
Operand order on pop

The first value you pop is the right operand and the second is the left one. For 8 2 - you pop 2 then 8 and compute 8 - 2 = 6, not 2 - 8. This only matters for - and /, which is exactly where exams test it.

int evalPostfix(const std::vector<std::string>& tokens) {
    Stackt<int> s;
    for (const std::string& t : tokens) {
        if (t == "+" || t == "-" || t == "*" || t == "/") {
            int right, left;
            s.pop(right);           // first pop  = right operand
            s.pop(left);            // second pop = left operand
            if      (t == "+") s.push(left + right);
            else if (t == "-") s.push(left - right);
            else if (t == "*") s.push(left * right);
            else               s.push(left / right);
        } else {
            s.push(std::stoi(t));   // operand
        }
    }
    int result;
    s.pop(result);
    return result;                  // stack should now be empty
}

(A full version would check stackIsEmpty() before each pop and after the last one, to report “not enough operands” and “too many operands”.)

Symbolic example (slides)

A B + C D E + - *
R1 C D E + - *        R1 = A + B
R1 C R2 - *           R2 = D + E
R1 R3 *               R3 = C - R2
RESULT                RESULT = R1 * R3

Numeric example (slides)

(2+3) * (2-(4+1)) in postfix is 2 3 + 2 4 1 + - *.

Token Action Stack (bottom → top)
2 push 2
3 push 2 3
+ pop 3, pop 2, push 2+3 5
2 push 5 2
4 push 5 2 4
1 push 5 2 4 1
+ pop 1, pop 4, push 4+1 5 2 5
- pop 5, pop 2, push 2−5 5 −3
* pop −3, pop 5, push 5×(−3) −15

Result: −15.

Self-study: infix to postfix

Operands go straight to the output. Operators wait on a stack until an operator of lower precedence (or a )) forces them out.

for each token, left to right:
    operand:    append to output
    '(':        push
    ')':        pop to output until '(' ; pop and discard the '('
    operator o: while the top is an operator with precedence >= o's:
                    pop it to output
                push o
at the end: pop everything left to output

* and / have higher precedence than + and -. The >= makes equal-precedence operators come out left to right (a - b - c → a b - c -).

Example A + B * C - D:

Token Output Operator stack
A A
+ A +
B A B +
* A B + *
C A B C + *
- A B C * + −
D A B C * + D −
end A B C * + D −

When - arrives, * (higher) and + (equal) are popped first, so the result is A B C * + D -.

Self-study: decimal to hexadecimal

Repeated division gives the digits right to left, but you print them left to right. A stack reverses them.

std::string toHex(int n) {        // n >= 0
    const char digits[] = "0123456789ABCDEF";
    if (n == 0) return "0";
    Stackt<char> s;
    while (n > 0) {
        s.push(digits[n % 16]);    // least significant digit first
        n /= 16;
    }
    std::string out;
    char c;
    while (!s.stackIsEmpty()) {
        s.pop(c);                  // most significant digit first
        out += c;
    }
    return out;
}

toHex(255): push F (255 % 16 = 15), n = 15; push F, n = 0. Pop → "FF". toHex(300): push C (12), push 2, push 1 → "12C". The same code with 2 or 8 instead of 16 converts to binary or octal.


8. Application: backtracking (maze)

A maze can be drawn as a graph of decision points (A at the entrance, G at the exit, with branches B to F in between). To find a path:

  • Pick a fixed order to try directions, e.g. South, East, North, West.
  • When you move onto a new track, push it on the stack.
  • When you hit a dead end (no untried track), backtrack: pop the last track and try the next option from the position below it.
  • When you reach the exit, the stack (bottom → top) is the path.

A simplified sketch of that idea (not the exact slide graph): from A you may try the B branch first, hit a dead end at F, pop back to A, and then take the C branch to G.

flowchart LR
    A["A (entrance)"] --> B["B"] --> D["D"] --> F["F"]
    A --> C["C"] --> E["E"] --> G["G (exit)"]

Later in the course the same search is written recursively, using the system’s run-time stack instead of our own. That algorithm is Depth First Search (DFS). Section 9 (Q20) traces a full grid maze.


9. Practice: tracing stacks

Slides: trace push and pop

Empty stack, then push(4), push(9), pop(), push(2), push(7), pop(). Writing the stack top-first:

[4] → [9,4] → [4] → [2,4] → [7,2,4] → [2,4]

The pops return 9 then 7. Final stack, top to bottom: 2, 4.

Slides: brackets

{ [ ( a + b ) * ( c - d ) ] } is balanced (section 6). Replacing the last } with ] makes it unbalanced, because the top opener is {.

Q16: array stack pop and peek

topIndex is -1 when empty, and data[topIndex] is the top.

bool pop(int& out) {
    if (empty()) return false;      // out unchanged
    out = data[topIndex--];
    return true;
}
bool peek(int& out) const {
    if (empty()) return false;
    out = data[topIndex];           // read only
    return true;
}

Start with [3, 7] (7 on top) and out = 0:

Call Returns out Stack after
peek true 7 [3, 7]
pop true 7 [3]
pop true 3 []
pop false 3 (unchanged) []

The failed pop leaves out at 3, not 0: a failed operation doesn’t touch the output argument.

Q17: linked stack pop

bool pop(int& out) {
    if (!topNode) return false;
    Node* old = topNode;
    out = old->value;
    topNode = old->next;
    delete old;
    return true;
}

Start with 11 on top and 4 below it:

Call Returns out topNode
1st pop true 11 node 4
2nd pop true 4 nullptr
3rd pop false 4 nullptr

Q18: match brackets

Show the stack after each bracket and stop at the first error (positions count from 1, spaces don’t count).

A. { [ ( ) ] }: { → {[ → {[( → {[ → { → empty. Every bracket matches: balanced.

B. { [ ( ] ) }: after three brackets the stack is {[(. At position 4 a ] arrives, but the top is (, which needs ). Error at position 4; stop there.

Q19: evaluate postfix

18 6 2 / - 3 4 + * (stack written bottom → top):

Token Stack
18 [18]
6 [18, 6]
2 [18, 6, 2]
/ [18, 3] (6 / 2)
- [15] (18 − 3)
3 [15, 3]
4 [15, 3, 4]
+ [15, 7]
* [105]

At each operator pop the right operand first, then the left. The answer is 105.

Q20: find a path in a maze

. is open, # is a wall, (row, column) from (1, 1). Try directions right, down, left, up; mark a cell visited when you push it; pop when there’s no unvisited open neighbour; stop when you push G.

      1 2 3 4 5
  1   S . . # #
  2   . # # # #
  3   . . . # #
  4   # # . . G
  1. Push (1,1), (1,2), (1,3) by going right.
  2. (1,3) is a dead end (right and down are walls), so pop (1,3). (1,2) has no unvisited open neighbour either (down is a wall), so pop (1,2).
  3. Back at (1,1): right is visited, so go down. Push (2,1), (3,1), (3,2), (3,3), (4,3), (4,4), (4,5) = G. Stop.

Path (the final stack, bottom → top): (1,1) → (2,1) → (3,1) → (3,2) → (3,3) → (4,3) → (4,4) → (4,5).


Quick self-test

What does LIFO mean, and which end of a stack is used?

Last In, First Out. Every push and pop happens at the top.

In the array stack, what is top for an empty stack and for a full one?

-1 when empty, MaxSize - 1 when full.

Why does Stackt need a copy constructor?

It owns a heap array. The default copy would share that array, so changes leak between copies and both destructors delete[] it.

In a linked stack, why is top the head of the list and not the tail?

Both insert and delete at the head are O(1). Deleting the tail of a singly linked list needs its predecessor, which takes a walk from the head.

Evaluating 8 2 -, which value do you pop first and what is the result?

2 first (the right operand), then 8; result 8 - 2 = 6.

Name the three ways the balanced-symbols check can fail.

A closer meets an empty stack; the popped opener doesn’t match the closer; openers are left on the stack at the end.

What is wrong with the slides’ Stack<T>::push?

When the stack is full it prints a message but still increments top and writes past the end of the array. It needs a return in the if.


Cheat sheet

  • Stack = LIFO; push and pop at the top only. Every operation is O(1).
  • ADT: construct, stackIsEmpty, stackIsFull, push(el), pop(el), stackTop(el) (peek, doesn’t remove).
  • Array: top = -1 empty, top == MaxSize - 1 full. Push stack[++top] = v;, pop v = stack[top--];.
  • Check full before push (overflow), empty before pop/top (underflow).
  • Array stack owns heap memory: needs a destructor (delete[]) and a deep-copy copy constructor.
  • Linked: top = head pointer, nullptr = empty, never full. Push = insert at head (pnew->next = top; top = pnew;). Pop = save value, cursor = top; top = top->next; delete cursor;.
  • Brackets: push openers; a closer pops and must match; empty-stack closer or leftovers at the end = unbalanced.
  • Postfix: operand → push; operator → pop right, pop left, push left op right; one value left at the end.
  • Infix → postfix: operands to output; operators wait on the stack; pop while top has precedence >=; ) pops to (.
  • Decimal → base b: push n % b, n /= b, then pop to print.
  • Backtracking: push each move, pop at a dead end; the stack is the path. Recursive version = DFS.