Kodewick
Start learning →
Stacks: last in, first out13 / 52

Stacks: last in, first out

Lesson 13 of 52 · Part 3 · Stacks and queues · about 15 minutes

A stack adds and removes at one end only, so the last in is the first out (LIFO); push, pop and top are O(1) with an array or a linked list, and the STL has std::stack.

A browser's Back button, an editor's Undo, functions calling each other and then returning one by one: all follow the same rule, the last one in is the first one out (LIFO, last in first out). A structure used that way is a stack. This lesson writes two stacks in C++ by hand, then looks at the STL's ready-made std::stack.

In and out at one end

A stack only works at one end, the top; the other end, the bottom, is never touched directly. Putting something in is push, taking it out is pop, and looking at the top is top. Stored in an array, the member t holds the index of the top element, and -1 for an empty stack.

data (5 slots, bottom at the bottom)

← top = -1
1void push(int x) { data[++t] = x; }2void pop() { t--; }3int top() const { return data[t]; }

Push 3, 7, 9, look at the top, then pop once: what comes out is the last one in, 9

++t adds first and then uses: push has to move to the free slot before storing. Write t++ and you overwrite the old top. The STL splits things the same way: top() only reads and pop() only removes, so to take the top away you call top() and then pop().

Choose one

How should push be written? (t holds the index of the top item; an empty stack has -1)

An array stack: a small class

An array has a fixed size, so before a push, check it isn't full (t == MAX - 1), and before a pop or a top, check it isn't empty (empty()). Exams call these overflow and underflow. Put the array and t in a class, and the outside can only reach them through these four functions.

main.cpp
1#include <iostream>2using namespace std;3 4const int MAX = 5;5 6class ArrayStack {7    int data[MAX];8    int t = -1;                           // index of the top, -1 when empty9public:10    bool push(int x) {11        if (t == MAX - 1) return false;   // full: overflow12        data[++t] = x;13        return true;14    }15    void pop() { t--; }                   // check empty() before calling16    int top() const { return data[t]; }17    bool empty() const { return t == -1; }18};19 20int main() {21    ArrayStack s;22    for (int i = 1; i <= 6; i++)23        if (!s.push(i * 10))24            cout << "push " << i * 10 << " failed: stack full\n";25    while (!s.empty()) {26        cout << s.top() << " ";27        s.pop();28    }29    cout << "\n";30    return 0;31}
Output
push 60 failed: stack full
50 40 30 20 10 

pop() returns nothing, and "the stack is empty" isn't said by a return value either: the caller asks empty() first. That way "empty" and "the top happens to be 0" never get mixed up, and it's used the same way as std::stack.

Guess the outputA wrong guess is fine

Push 1 2 3, pop, push 4, then pop twice. What does it print?

1#include <iostream>2using namespace std;3 4int main() {5    int data[5], t = -1;6    data[++t] = 1;7    data[++t] = 2;8    data[++t] = 3;9    cout << data[t--] << " ";10    data[++t] = 4;11    cout << data[t--] << " ";12    cout << data[t--] << "\n";13    return 0;14}
Choose one

An array stack with const int MAX = 5;, t starting at -1. When is it full?

Exercise 1

Write an array stack

Fill in the four functions of ArrayStack (push returns false when full) so the program prints 3 and then 3 2 1.

It should print
3
3 2 1
exercise1.cpp
1#include <iostream>2using namespace std;3 4const int MAX = 3;5 6class ArrayStack {7    int data[MAX];8    int t = -1;9public:10    bool push(int x) {11        // full: return false; otherwise move t first, then store12        return true;13    }14    void pop() {15        // move t down one16    }17    int top() const { return 0; }       // make it the top18    bool empty() const { return true; } // make it: empty only when t is -119};20 21int main() {22    ArrayStack s;23    int ok = s.push(1) + s.push(2) + s.push(3) + s.push(4);24    cout << ok << "\n";25    while (!s.empty()) {26        cout << s.top() << " ";27        s.pop();28    }29    cout << "\n";30    return 0;31}
Output
Press Run or Ctrl+Enter

Linked stacks: push is insert at the head

Store the stack in a linked list with the head as the top: push news a node at the head, pop removes the head node and deletes it. There's no "full" to check (you can push as long as there's memory), and every operation is still O(1).

head↓
9c
7b
3a
nullptr

A linked stack, push 9 then pop: the new node points at the old top; pop moves head back and deletes the old node
main.cpp
1#include <iostream>2using namespace std;3 4struct Node {5    int val;6    Node* next;7    Node(int v, Node* n) : val(v), next(n) {}8};9 10class LinkedStack {11    Node* head = nullptr;                 // the top is the head of the list12public:13    void push(int x) {14        head = new Node(x, head);         // the new node points at the old top, then becomes the top15    }16    void pop() {17        Node* old = head;18        head = head->next;19        delete old;20    }21    int top() const { return head->val; }22    bool empty() const { return head == nullptr; }23    ~LinkedStack() {                      // on the way out, delete the nodes still left24        while (!empty()) pop();25    }26};27 28int main() {29    LinkedStack s;30    s.push(3);31    s.push(7);32    s.push(9);33    while (!s.empty()) {34        cout << s.top() << " ";35        s.pop();36    }37    cout << "\n";38    return 0;39}
Output
9 7 3 

pop first remembers the top in old, moves head to the node below, and only then does delete old: the other way round, head->next would read memory that has already been given back.

The C edition has to pass Node **top to change the caller's top pointer. A class doesn't have that problem: head is the object's own member, and push and pop change it directly. What you new you must delete: the destructor ~LinkedStack() deletes the remaining nodes one by one when s leaves main, and every hand-written structure in this course does the same.

Array stackLinked stack
push / pop / topO(1)O(1)
Check for full?Yes (fixed size)No
Extra spaceNoneOne pointer per element
Each pushWrites one slotOne new
Put in orderDrag, or use the arrows

Put these 3 lines of a linked stack’s pop in order so the program prints 3 2 1 (top to bottom the stack is 3 2 1).

  1. delete old;
  2. Node* old = head;
  3. head = head->next;
Should print
3 2 1
Choose one

When a singly linked list is used as a stack, why is the head of the list the top, not the tail?

Pop orders

The exam favourite: items are pushed in the order 1 2 3; which pop orders are possible? Pushes and pops can be interleaved: push 1, pop, push 2, push 3, pop, pop gives 1 3 2.

stack

Pushing 1 2 3 in order and popping in between gives the pop order 1 3 2

Of the six orders, only one is impossible:

Pop orderPossible?How
1 2 3YesPop after every push
1 3 2Yespush 1 pop, push 2 push 3, pop pop
2 1 3Yespush 1 push 2, pop pop, push 3 pop
2 3 1Yespush 1 push 2, pop, push 3, pop pop
3 2 1YesPush everything, then pop everything
3 1 2No3 out first means 1 and 2 are both still inside, 2 on top of 1, so the next one out must be 2

The rule: when a number is popped, the numbers pushed before it that are still inside must come out in reverse push order. n numbers have C(2n, n)/(n + 1) valid orders (the Catalan numbers); for 3 numbers that's 5. This chapter's patterns lesson writes a program that checks an order.

Choose one

Pushed in the order 1 2 3 4: which of these cannot be the pop order?

Choose one

Pushed in the order 1 2 3 4: how many pop orders are possible?

With the STL

The STL's stack is std::stack (header <stack>). Its four functions are the same as the hand-written ones, push, pop, top, empty, plus size.

main.cpp
1#include <iostream>2#include <stack>3#include <vector>4using namespace std;5 6int main() {7    stack<int> s;                 // by default there's a deque<int> inside8    s.push(3);9    s.push(7);10    s.push(9);11    cout << "size " << s.size() << ", top " << s.top() << "\n";12    s.pop();                      // removes only, returns nothing13    cout << "after pop, top " << s.top() << "\n";14 15    stack<int, vector<int>> v;    // kept in a vector instead16    v.push(1);17    v.push(2);18    v.push(3);19    while (!v.empty()) {20        cout << v.top() << " ";21        v.pop();22    }23    cout << "\n";24    return 0;25}
Output
size 3, top 9
after pop, top 7
3 2 1 

std::stack stores nothing itself: it's a container adaptor. Inside it holds another container (a deque by default; a vector or a list if you say so) and shows only its back end: push is push_back, pop is pop_back, top is back. Everything else is hidden: no indexing, no iterating, just the top.

OperationWhat it doesCost
push(x)The container's push_backO(1) (a vector sometimes grows: amortised O(1))
pop()pop_back, returns nothingO(1)
top()back(), a reference to the topO(1)
empty() / size()Asks the containerO(1)

Calling top() or pop() on an empty stack doesn't raise an error; it's undefined behaviour: you may read garbage, or the program may crash. So, as with the hand-written one, ask empty() first.

In interviews: For a stack problem just use stack<int>; many people use a plain vector<int> as the stack (push_back, back, pop_back), which also lets you look inside by index, the usual way to write a monotonic stack. If asked "why doesn't pop return the value?": with top and pop split, an error while taking the value (say a copy that throws) can't lose the top.

Choose one

stack<int> s; already holds some numbers. To take the top out into y, so it is no longer in the stack, you write:

Exercise 2

Reverse a string with a stack

Use a stack<char>: push the characters one by one, then take the top and pop, one at a time, building the reversed string.

It should print
kcats
exercise2.cpp
1#include <iostream>2#include <stack>3#include <string>4using namespace std;5 6int main() {7    string s = "stack";8    stack<char> st;9    string out;10    // push every character; then append the top to out, and pop11    cout << out << "\n";12    return 0;13}
Output
Press Run or Ctrl+Enter

Summary

Take-away

Stacks: in and out at the top, last in first out

  • Array stack: t starts at -1; push adds then stores; full is t == MAX - 1
  • Linked stack: push inserts at the head (new), pop removes the head (delete), never full
  • top only reads, pop only removes; ask empty() first
  • std::stack is a layer over a deque; push, pop and top are all O(1)
1data[++t] = x;          // hand-written push2stack<int> s;3s.push(x);4int y = s.top();5s.pop();