Kodewick
Start learning →
Stacks: last in, first out11 / 50

Stacks: last in, first out

Lesson 11 of 50 · Part 3 · Stacks and queues · about 14 minutes

A stack is last in, first out: you push and pop at the top only, as in s->data[++s->top] = x, with top == -1 meaning empty, and every operation is O(1).

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.

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. Stored in an array, top holds the index of the top element, and -1 for an empty stack.

data (5 slots, bottom at the bottom)

← top = -1
1void push(Stack *s, int x) { s->data[++s->top] = x; }2int pop(Stack *s) { return s->data[s->top--]; }

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

++s->top adds first and then uses; s->top-- uses first and then subtracts. push has to move to the free slot before storing, pop has to take before moving. Get that backwards and you either overwrite the top or read an empty slot.

Choose one

How should push be written? (top points at the top element, and is -1 when the stack is empty.)

Exercise 1

Reverse a string with a stack

Push the string's characters one by one, then pop them all into a new string, which comes out reversed.

It should print
kcats
exercise1.c
1#include <stdio.h>2#include <string.h>3 4int main(void) {5    char s[] = "stack";6    char st[16], out[16];7    int top = -1, k = 0;8    // push each character; then pop into out[k++]9    out[k] = '\0';10    printf("%s\n", out);11    return 0;12}
Output
Press Run or Ctrl+Enter

Array stacks: check full and empty

An array has a fixed size, so before a push, check it isn't full (top == MAX - 1), and before a pop, check it isn't empty (top == -1). Exams call these overflow and underflow.

main.c
1#include <stdio.h>2 3#define MAX 54 5typedef struct {6    int data[MAX];7    int top;8} Stack;9 10int push(Stack *s, int x) {11    if (s->top == MAX - 1) return 0;   // full12    s->data[++s->top] = x;13    return 1;14}15 16int pop(Stack *s, int *x) {17    if (s->top == -1) return 0;        // empty18    *x = s->data[s->top--];19    return 1;20}21 22int main(void) {23    Stack s = {{0}, -1};24    for (int i = 1; i <= 6; i++)25        if (!push(&s, i * 10))26            printf("push %d failed: the stack is full\n", i * 10);27    int x;28    while (pop(&s, &x))29        printf("%d ", x);30    printf("\n");31    return 0;32}
Output
push 60 failed: the stack is full
50 40 30 20 10 

pop hands the value back through int *x and its return value only says whether it worked: that way "the stack is empty" and "the value happened to be 0" can't be confused.

Guess the outputA wrong guess is fine

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

1#include <stdio.h>2 3int main(void) {4    int data[5], top = -1;5    data[++top] = 1;6    data[++top] = 2;7    data[++top] = 3;8    printf("%d ", data[top--]);9    data[++top] = 4;10    printf("%d ", data[top--]);11    printf("%d\n", data[top--]);12    return 0;13}
Choose one

An array stack with #define MAX 5 starts with top at -1. When is it full?

Exercise 2

Write push and pop

Finish the array stack's push and pop (both check full or empty first) so the program prints the two lines below.

It should print
3
3 2 1
exercise2.c
1#include <stdio.h>2 3#define MAX 34 5typedef struct {6    int data[MAX];7    int top;8} Stack;9 10int push(Stack *s, int x) {11    // full: return 0; otherwise move top, then store12    return 1;13}14 15int pop(Stack *s, int *x) {16    // empty: return 0; otherwise take, then move top17    return 1;18}19 20int main(void) {21    Stack s = {{0}, -1};22    int ok = push(&s, 1) + push(&s, 2) + push(&s, 3) + push(&s, 4);23    printf("%d\n", ok);24    int x;25    while (pop(&s, &x))26        printf("%d ", x);27    printf("\n");28    return 0;29}
Output
Press Run or Ctrl+Enter

Linked stacks: push is head insertion

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

main.c
1#include <stdio.h>2#include <stdlib.h>3 4typedef struct Node {5    int data;6    struct Node *next;7} Node;8 9Node *new_node(int data, Node *next) {10    Node *n = malloc(sizeof(Node));11    n->data = data;12    n->next = next;13    return n;14}15 16void push(Node **top, int x) {17    *top = new_node(x, *top);          // the new node points at the old top, then becomes the top18}19 20int pop(Node **top, int *x) {21    if (*top == NULL) return 0;22    Node *old = *top;23    *x = old->data;24    *top = old->next;25    free(old);26    return 1;27}28 29int main(void) {30    Node *top = NULL;31    push(&top, 3);32    push(&top, 7);33    push(&top, 9);34    int x;35    while (pop(&top, &x))36        printf("%d ", x);37    printf("\n");38    return 0;39}
Output
9 7 3 

Why Node **top: push and pop both have to change the caller's top pointer itself, so they need its address. With Node *top they would only change the function's own copy.

Array stackLinked stack
push / popO(1)O(1)
Check for fullyes (fixed size)no
Extra spacenoneone pointer per element
Choose one

Suppose push took Node *top instead. After Node *top = NULL; push(top, 3); in main, what is top in main?

Put in orderDrag, or use the arrows

Put the 4 lines of pop in order so the program prints 3 2 1 (the stack holds 3 2 1 from top to bottom).

  1. free(old);
  2. Node *old = *top;
  3. *x = old->data;
  4. *top = old->next;
Should print
3 2 1

Pop orders

A favourite exam question: pushed in the order 1 2 3, which orders can they be popped in? Pushes and pops can be interleaved: push 1, pop, push 2, push 3, pop, pop gives 1 3 2.

stack

Pushing 1 2 3 with pops in between gives the pop order 1 3 2

Of the six orders, only one can't happen:

Pop orderPossible?How
1 2 3yespop after each 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 in, 2 above 1, so the next out can only be 2

The rule: when a number is popped, the ones pushed before it and not yet popped must come out in the reverse of the order they went in. n numbers have C(2n, n)/(n + 1) possible orders (the Catalan numbers), 5 for 3 numbers. This chapter's patterns lesson writes a program to decide.

Choose one

The push order is 1 2 3 4. Which one can not be a pop order?

Choose one

The push order is 1 2 3 4. How many different pop orders are possible?

Summary

Take-away

A stack: in and out at the top only, last in first out

  • Array stack: top starts at -1; push adds then stores, pop takes then subtracts
  • Full: top == MAX - 1; empty: top == -1
  • Linked stack: push inserts at the head, pop deletes it; never full
  • push and pop are both O(1)
1s->data[++s->top] = x;    // push2x = s->data[s->top--];    // pop