Stacks: last in, first out
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)
379taken1void push(Stack *s, int x) { s->data[++s->top] = x; }2int pop(Stack *s) { return s->data[s->top--]; }
++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.
How should push be written? (top points at the top element, and is -1 when the stack is empty.)
top points at is already in use, so you first move up to the free slot and then store: increment first, ++s->top. s->top++ uses the old value and writes x over the current top; without changing top you keep writing into the same slot.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.
kcats
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}
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.
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}
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.
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}
An array stack with #define MAX 5 starts with top at -1. When is it full?
MAX - 1, nothing more fits. By the time top == MAX you have already written past the end; top == -1 means empty.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.
3 3 2 1
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}
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).
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}
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 stack | Linked stack | |
|---|---|---|
| push / pop | O(1) | O(1) |
| Check for full | yes (fixed size) | no |
| Extra space | none | one pointer per element |
Suppose push took Node *top instead. After Node *top = NULL; push(top, 3); in main, what is top in main?
Node *top the function gets a copy of the top in main. It changes the copy, main’s top stays NULL, and the new node is leaked. That is why you pass &top and declare the parameter as Node **top.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).
free(old);Node *old = *top;*x = old->data;*top = old->next;
3 2 1
old first; only then can you take its value and move *top down one. free(old) must come last: free it first and old->data reads memory that has already been given back.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
123Of the six orders, only one can't happen:
| Pop order | Possible? | How |
|---|---|---|
| 1 2 3 | yes | pop after each push |
| 1 3 2 | yes | push 1 pop, push 2 push 3, pop pop |
| 2 1 3 | yes | push 1 push 2, pop pop, push 3 pop |
| 2 3 1 | yes | push 1 push 2, pop, push 3, pop pop |
| 3 2 1 | yes | push everything, then pop everything |
| 3 1 2 | no | 3 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.
The push order is 1 2 3 4. Which one can not be a pop order?
The push order is 1 2 3 4. How many different pop orders are possible?
Summary
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