Chapter 6: Stacks

Data Structures and Algorithms with C
LIFOStack ADTpush / popOverflowLinked stackCall stackMultiple stacks
Sercan KÜLCÜ · Giresun University · Computer Engineering

Introduction

Learning Outcomes

Define LIFO

Model a stack as a list S = {a0, …, an−1} and identify its bottom and top.

Implement with an array

Write push/pop around a top index and check for overflow and underflow.

Build a linked stack

Allocate nodes with malloc, link them, and free each node you remove.

Understand the call stack

Explain why function calls behave like a stack and why the call stack can overflow.

Make design decisions

Choose between a fixed array, a growable array, and a linked list by cost.

Manage multiple stacks

Share one memory array among n stacks using top[i] and boundary[i].

The Stack ADT

The Stack: Last In, First Out

A stack is an ordered list in which all insertions and deletions happen at one end only. For S = {a0, a1, …, an−1}, a0 is the bottom and an−1 is the top. The last item in is the first one out: LIFO (last-in-first-out).

wallentry / exit (one end)nearest car leaves firstABCD

Cars parked in a one-car-wide dead end: the last one in (D) has to leave first.

Don't confuse the stack ADT with the heap data structure (Chapter 13) or with the heap memory that malloc manages.

The Stack ADT

How a Stack Grows and Shrinks

A[0][1][2][3][4]top = 0A pushed

A pushed → A is now on top; top = 0.

A[0]B[1][2][3][4]top = 1B pushed

B pushed → B is now on top; top = 1.

A[0]B[1]C[2][3][4]top = 2C pushed

C pushed → C is now on top; top = 2.

A[0]B[1]C[2]D[3][4]top = 3D pushed

D pushed → D is now on top; top = 3.

A[0]B[1]C[2]D[3]E[4]top = 4E pushed

E pushed → E is now on top; top = 4.

A[0]B[1]C[2]D[3][4]top = 3EE popped

Deletion happens only at the top: the first item removed is E, the last one added. D is on top again; top = 3.

  • Push order: A, B, C, D, E.
  • Pop order (if we removed them all): E, D, C, B, A, exactly reversed.
  • To reach an item in the middle (say B), everything above it must be popped first.
  • This restriction is not a flaw but a contract: “the last job opened is the first one closed.”

The Stack ADT

Abstract Data Type: Stack

OperationMeaningPrecondition / error
stack_create(max)Empty stack holding at most max items—
stack_full(S)True if it holds max items—
push(S, x)Puts x on topOverflow if full
stack_empty(S)True if it holds no items—
pop(S)Removes and returns the top itemUnderflow if empty
stack_top(S) · peekReads the top item without removing itError if empty

An ADT says what the operations do, not how. The same interface can be implemented with a fixed array, a growable array, or a linked list (Horowitz–Sahni, ADT 3.1).

The Stack ADT

Where Stacks Show Up

Call stack

Every function call pushes a frame holding its return address and local variables.

Expression evaluation

Compilers use a stack to convert infix to postfix and to evaluate postfix.

Backtracking

At a dead end in a maze, go back to the most recent fork.

Bracket matching

Every closing bracket must match the most recently opened one.

Undo

An editor pushes every action; Ctrl+Z undoes the latest one.

Depth-first search

DFS keeps the vertices still to visit on a stack.

The Stack ADT

push and pop Only at the Top

Push four times, then pop: items come out in reverse order. Popping an empty stack is underflow.

Array-Based Stack

Array-Based Stack: the top Index

[0][1][2][3][4]top = -1empty stacktop < 0 → emptypop → underflowA[0]B[1]C[2]D[3]E[4]top = 4full stack
Empty: top < 0

An empty stack has top = −1. Popping from it is an underflow error.

Full: top ≥ MAX_STACK_SIZE − 1

Pushing onto it is an overflow error.

Item count = top + 1

Mixing the two up is the classic off-by-one bug.

What goes wrong?

C does not check array bounds: an unchecked push overwrites neighboring memory.

Array-Based Stack

Array-Based Stack: C Definitions

#include <stdio.h>
#include <stdlib.h>
#define MAX_STACK_SIZE 101

typedef struct {
    int key;
    /* other fields */
} element;

element stack[MAX_STACK_SIZE];

void stack_full(void) {
    printf("Stack is full!!!\n"); exit(-1);
}
void stack_empty(void) {
    printf("Stack is empty!!!\n"); exit(-2);
}
  • element: the record stored on the stack; for now its only field is key.
  • The stack is a global array; top is passed in by address from the caller.
  • The error routines print a message and end the program with exit.
Instructor “Do it this way and you get a zero, maybe even negative points. How many times have we covered this here?”

Array-Based Stack

Push and Pop Routines

void push(int *top, element item) {
    if (*top >= MAX_STACK_SIZE - 1)  /* any room? */
        stack_full();         /* warn and exit */
    stack[++*top] = item;     /* bump the index first */
}                             /* then store the item */

element pop(int *top) {
    if (*top < 0)
        stack_empty();        /* warn and exit if empty */
    return stack[(*top)--];   /* return, then decrement */
}
stack[++*top]

*top is incremented first, then the item is written at the new index: on an empty stack, −1 → 0.

stack[(*top)--]

The item at the old index is read first, then *top is decremented. The parentheses matter: *top-- would decrement the pointer itself.

Instructor “Normally, a variable that appears as ‘*param’ in a routine's formal parameter list must also be used as ‘*param’ inside the routine.”

Array-Based Stack

A Precedence Trap in C: * with ++/--

ExpressionHow C parses itResult
++*top++(*top): increment the int it points toCorrect (push)
(*top)--use the int it points to, then decrement itCorrect (pop)
*top--*(top--): decrement the pointer, read the old addressWrong: top is unchanged
*top++*(top++): advance the pointerWrong
Rule

Postfix ++/-- binds tighter than unary *; prefix ++ and * share a level and associate right to left.

Why pass the address?

top belongs to the caller; we pass &top so the routine can change it (C passes arguments by value).

Array-Based Stack · Run the code step by step

Code Trace: Array-Based Stack

[0][1][2][3]top = -1empty stacktop = −1

In main, top = −1 (empty). Push A, B, C; pop; push D, E, F. MAX_STACK_SIZE = 4.

[0][1][2][3]top = -1

-1 ≥ 3? No, there is room.

A[0][1][2][3]top = 0

++*top → top = 0, then stack[0] = A.

A[0][1][2][3]top = 0

0 ≥ 3? No, there is room.

A[0]B[1][2][3]top = 1

++*top → top = 1, then stack[1] = B.

A[0]B[1][2][3]top = 1

1 ≥ 3? No, there is room.

A[0]B[1]C[2][3]top = 2

++*top → top = 2, then stack[2] = C.

A[0]B[1]C[2][3]top = 2

2 < 0? No, the stack is not empty.

A[0]B[1]C[2][3]top = 1

stack[2] = C is returned, then top = 1. The old value stays in the cell, but it is no longer part of the stack.

A[0]B[1][2][3]top = 1

1 ≥ 3? No, there is room.

A[0]B[1]D[2][3]top = 2

++*top → top = 2, then stack[2] = D.

A[0]B[1]D[2][3]top = 2

2 ≥ 3? No, there is room.

A[0]B[1]D[2]E[3]top = 3

++*top → top = 3, then stack[3] = E.

A[0]B[1]D[2]E[3]top = 3

3 ≥ 3? Yes: no room left!

A[0]B[1]D[2]E[3]top = 3

stack_full() prints a message and ends the whole program with exit(-1). That is a heavy-handed reaction for library code; a version that returns bool leaves the decision to the caller.

void push(int *top, element item) {
  if (*top >= MAX_STACK_SIZE - 1)
    stack_full();  /* "Stack is full!!!", exit */
  stack[++*top] = item;
}
element pop(int *top) {
  if (*top < 0)
    stack_empty(); /* "Stack is empty!!!", exit */
  return stack[(*top)--];
}

Array-Based Stack

Better Design: the Stack as an Object

#include <stdbool.h>
#define CAP 100

typedef struct {
    int data[CAP];
    int top;               /* -1 when empty */
} Stack;

void stack_init(Stack *s) { s->top = -1; }
bool stack_empty(const Stack *s) { return s->top < 0; }
bool stack_full(const Stack *s)  { return s->top == CAP - 1; }
int  stack_size(const Stack *s)  { return s->top + 1; }
bool stack_top(const Stack *s, int *x) {
    if (stack_empty(s)) return false;
    *x = s->data[s->top];  return true;
}
  • The array and top live in one struct, so two stacks can coexist in a program without interfering.
  • No globals: every routine takes the stack as a parameter.
  • On error the routine returns false instead of calling exit; the caller decides what to do.
Instructor “Global variables are forbidden! Inside, use a stack, a queue, local variables, whatever you need. But no globals!”

Array-Based Stack · Run the code step by step

Code Trace: push / pop Returning bool

[0][1][2]top = -1CAP = 3size = top + 1 = 0

After stack_init(&s), top = −1. Push 5, 8, 2, 9, then pop four times. CAP = 3.

[0][1][2]top = -1CAP = 3size = top + 1 = 0

-1 == 2? No, there is room.

5[0][1][2]top = 0CAP = 3size = top + 1 = 1

++s->top → 0; data[0] = 5; returns true.

5[0][1][2]top = 0CAP = 3size = top + 1 = 1

0 == 2? No, there is room.

5[0]8[1][2]top = 1CAP = 3size = top + 1 = 2

++s->top → 1; data[1] = 8; returns true.

5[0]8[1][2]top = 1CAP = 3size = top + 1 = 2

1 == 2? No, there is room.

5[0]8[1]2[2]top = 2CAP = 3size = top + 1 = 3

++s->top → 2; data[2] = 2; returns true.

5[0]8[1]2[2]top = 2CAP = 3size = top + 1 = 3

top == CAP − 1 (2 == 2) → return false. The program keeps running; the caller learns about the overflow.

5[0]8[1]2[2]top = 1CAP = 3size = top + 1 = 2

Not empty; *x = data[2] = 2, then top = 1.

5[0]8[1][2]top = 0CAP = 3size = top + 1 = 1

Not empty; *x = data[1] = 8, then top = 0.

5[0][1][2]top = -1CAP = 3size = top + 1 = 0

Not empty; *x = data[0] = 5, then top = -1.

[0][1][2]top = -1CAP = 3size = top + 1 = 0

top < 0 → return false: underflow, and *x is left untouched.

bool push(Stack *s, int x) {
  if (s->top == CAP - 1) return false; /* overflow */
  s->data[++s->top] = x;
  return true;
}
bool pop(Stack *s, int *x) {
  if (s->top < 0) return false;   /* underflow */
  *x = s->data[s->top--];
  return true;
}

Array-Based Stack

Write It as a Component: stack.h and stack.c

/* stack.h: all the client sees */
#ifndef STACK_H
#define STACK_H
#include <stdbool.h>
typedef struct Stack Stack;  /* opaque */
Stack *stack_create(int capacity);
void stack_destroy(Stack *s);
bool push(Stack *s, int x);
bool pop(Stack *s, int *x);
bool stack_empty(const Stack *s);
#endif

Client code cannot see inside the struct; it only calls the operations. Even if the implementation switches from an array to a linked list, client code stays the same.

/* stack.c: implementation */
struct Stack { int *data; int top, cap; };

Stack *stack_create(int cap) {
  Stack *s = malloc(sizeof *s);
  if (s == NULL) return NULL;
  s->data = malloc(cap * sizeof *s->data);
  if (s->data == NULL) {
    free(s);  return NULL;
  }
  s->top = -1;  s->cap = cap;
  return s;
}
void stack_destroy(Stack *s) {
  if (s) { free(s->data); free(s); }
}

Array-Based Stack · Run the code step by step

Code Trace: Reversing a String with a Stack

0V1I2S3I4Tstop = -1

Input "VISIT"; an empty stack is set up.

0V1I2S3I4T▲ isVtop = 0

s[0] = 'V' ≠ '\0' → push('V').

0V1I2S3I4T▲ isVItop = 1

s[1] = 'I' ≠ '\0' → push('I').

0V1I2S3I4T▲ isVIStop = 2

s[2] = 'S' ≠ '\0' → push('S').

0V1I2S3I4T▲ isVISItop = 3

s[3] = 'I' ≠ '\0' → push('I').

0V1I2S3I4T▲ isVISITtop = 4

s[4] = 'T' ≠ '\0' → push('T').

0T1I2S3I4T▲ isVISItop = 3

pop → 'T', s[0] = 'T'.

0T1I2S3I4T▲ isVIStop = 2

pop → 'I', s[1] = 'I'.

0T1I2S3I4T▲ isVItop = 1

pop → 'S', s[2] = 'S'.

0T1I2S3I4T▲ isVtop = 0

pop → 'I', s[3] = 'I'.

0T1I2S3I4V▲ istop = -1

pop → 'V', s[4] = 'V'.

0T1I2S3I4Vstop = -1

The stack is empty: pop returns false and the loop ends. Result: "TISIV". n pushes + n pops → O(n).

void reverse(char *s) {
  Stack st;  int c, i;
  stack_init(&st);
  for (i = 0; s[i] != '\0'; i++)
    push(&st, s[i]);    /* assume CAP suffices */
  for (i = 0; pop(&st, &c); i++)
    s[i] = (char)c;
}

Linked Stack

Implementing a Stack with a Linked List

topCBANULLtop (last pushed)bottom (first pushed)

A, B, C pushed in that order: top points to the head of the list.

  • Each item is a node: data plus a link to the next node.
  • Insert and delete at the head: both O(1), no shifting.
  • No capacity limit: overflow happens only if malloc fails.
Why the head and not the tail? Popping at the tail means stepping back from the last node, and finding the previous node in a singly linked list costs O(n). Hence top = head of the list.
Instructor “Top holds the head of the list. Deleting means moving back from the last item, so either you keep the tail with two pointers or you keep the head with one.”

Linked Stack · Run the code step by step

Code Trace: Linked push

*topNULL

Start: node *top = NULL; (empty stack). Push 10, 20, 30 in turn.

*topNULL?← new_node

malloc allocates a new node; if it is not NULL we continue. Its fields are still undefined.

*topNULL10← new_node

new_node->data = 10.

*topNULL10NULL← new_node

new_node->link = *top: the new node points to the old top (NULL). Order matters: link first, then change *top.

*top10NULL← new_node

*top = new_node: the caller's top now points to 10. Stack: 10.

*top?← new_node10NULL

malloc allocates a new node; if it is not NULL we continue. Its fields are still undefined.

*top20← new_node10NULL

new_node->data = 20.

*top20← new_node10NULL

new_node->link = *top: the new node points to the old top (node(10)). Order matters: link first, then change *top.

*top20← new_node10NULL

*top = new_node: the caller's top now points to 20. Stack: 20 → 10.

*top?← new_node2010NULL

malloc allocates a new node; if it is not NULL we continue. Its fields are still undefined.

*top30← new_node2010NULL

new_node->data = 30.

*top30← new_node2010NULL

new_node->link = *top: the new node points to the old top (node(20)). Order matters: link first, then change *top.

*top30← new_node2010NULL

*top = new_node: the caller's top now points to 30. Stack: 30 → 20 → 10.

*top302010NULL

After three pushes: 30 → 20 → 10 → NULL. Each push does a constant amount of work: O(1).

bool push(node **top, int x) {
  node *new_node = malloc(sizeof *new_node);
  if (new_node == NULL) return false; /* no memory */
  new_node->data = x;
  new_node->link = *top;  /* point to old top */
  *top = new_node;        /* new top */
  return true;
}

Linked Stack · Run the code step by step

Code Trace: Linked pop

*top302010NULL

Stack: 30 → 20 → 10. We call pop four times; main prints each successful result.

*top302010NULLold

old = *top: just a copy of a pointer; no new memory is allocated.

*top302010NULLold

*x = 30 (read the value before the node is freed).

*top302010NULLold

*top = old->link → node(20).

*top30freed2010NULL

free(old): node 30's memory goes back to the system. main prints 30.

*top30freed2010NULLold

old = *top: just a copy of a pointer; no new memory is allocated.

*top30freed2010NULLold

*x = 20 (read the value before the node is freed).

*top30freed2010NULLold

*top = old->link → node(10).

*top30freed20freed10NULL

free(old): node 20's memory goes back to the system. main prints 20.

*top30freed20freed10NULLold

old = *top: just a copy of a pointer; no new memory is allocated.

*top30freed20freed10NULLold

*x = 10 (read the value before the node is freed).

*topNULL30freed20freed10NULLold

*top = old->link → NULL.

*topNULL30freed20freed10NULLfreed

free(old): node 10's memory goes back to the system. main prints 10.

*topNULL30freed20freed10NULLfreed

old = NULL → the stack is empty, return false. The loop stops here.

bool pop(node **top, int *x) {
  node *old = *top;        /* no malloc! */
  if (old == NULL) return false;  /* empty */
  *x = old->data;
  *top = old->link;        /* advance top */
  free(old);               /* release memory */
  return true;
}

Linked Stack

Who Owns the Memory in a Linked Stack

typedef struct node {
    int data;
    struct node *link;
} node;

void stack_clear(node **top) {
    while (*top != NULL) {
        node *old = *top;
        *top = old->link;
        free(old);
    }
}                  /* afterwards *top == NULL */
  • old is a pointer variable, not a new node: it needs no malloc.
  • Save the link first (*top = old->link), then call free: the other way round reads freed memory.
  • Call stack_clear before the program ends: every malloc needs a matching free.
Instructor “You don't need to malloc space for every pointer. There's no such rule!”
Instructor “If you don't learn pointers now, you may still not know them in your senior year.”

Linked Stack

Array-Based or Linked?

CriterionFixed arrayGrowable arrayLinked list
CapacityFixed at compile time×2 as neededUntil memory runs out
push / popO(1)O(1) amortizedO(1), a malloc per push
Extra memory per itemNoneNone (except unused capacity)One pointer (8 bytes)
Cache behaviorVery goodVery goodPoor (nodes scattered)
OverflowPossibleOnly if realloc failsOnly if malloc fails
Bug riskBounds checksrealloc's return valueforgotten free, dangling pointer

If the maximum size is known, use a fixed array; if not, a growable array is usually fastest in practice. A linked stack suits cases where the nodes already live in other structures or are created and destroyed one at a time.

The Call Stack

The Call Stack Overflows Too

The call stack is a stack: each call pushes a frame holding the return address, parameters, and locals, and return pops it. The most recently called function finishes first.

Infinite recursion

Recursion with no base case, or one it never reaches, pushes a frame per call; when the system stack (typically a few MB) fills up, the program crashes with a stack overflow.

Large local arrays

A local array such as int a[1000000]; lives in the frame and can overflow the stack on its own. Put large data on the heap with malloc.

Returning a local's address

return &local; is a bug: once the frame is popped, other calls reuse that memory (a dangling pointer).

Removing recursion

Any recursive algorithm can be turned into a loop that maintains its own stack.

Multiple Stacks

Multiple Stacks: Start with Two

0318213456672▲ top1 = 2▲ top2 = 6stack 1 grows rightstack 2 grows left
  • Stack 1 grows up from 0, stack 2 grows down from m−1.
  • Empty: top1 = −1, top2 = m.
  • Full: top1 + 1 == top2, when the two meet.
Advantage: even if one stack holds few items and the other many, no cell is wasted; the array fills only when the total reaches m. With three or more stacks, this trick no longer works.

Multiple Stacks · Run the code step by step

Code Trace: n Stacks, One Memory

01234567891011stack 0: top[0] = -1stack 1: top[1] = 3stack 2: top[2] = 7boundary = [-1, 3, 7, 11]

MEM = 12, n = 3: 4 cells each; top[i] = boundary[i] = (m/n)·i − 1, boundary[n] = m − 1.

051234567891011stack 0: top[0] = 0stack 1: top[1] = 3stack 2: top[2] = 7boundary = [-1, 3, 7, 11]

Room; memory[0] = 5, top[0] = 0.

0512347567891011stack 0: top[0] = 0stack 1: top[1] = 4stack 2: top[2] = 7boundary = [-1, 3, 7, 11]

Room; memory[4] = 7, top[1] = 4.

05192347567891011stack 0: top[0] = 1stack 1: top[1] = 4stack 2: top[2] = 7boundary = [-1, 3, 7, 11]

Room; memory[1] = 9, top[0] = 1.

051923475678491011stack 0: top[0] = 1stack 1: top[1] = 4stack 2: top[2] = 8boundary = [-1, 3, 7, 11]

Room; memory[8] = 4, top[2] = 8.

0519223475678491011stack 0: top[0] = 2stack 1: top[1] = 4stack 2: top[2] = 8boundary = [-1, 3, 7, 11]

Room; memory[2] = 2, top[0] = 2.

05192238475678491011stack 0: top[0] = 3stack 1: top[1] = 4stack 2: top[2] = 8boundary = [-1, 3, 7, 11]

Room; memory[3] = 8, top[0] = 3.

05192238475678491011stack 0: top[0] = 3stack 1: top[1] = 4stack 2: top[2] = 8boundary = [-1, 3, 7, 11]

top[0] == boundary[1] (3 == 3) → stack 0 is full, yet 6 cells are free! Horowitz's stack_full would shift stacks.

0519223845678491011stack 0: top[0] = 3stack 1: top[1] = 3stack 2: top[2] = 8boundary = [-1, 3, 7, 11]

top[1] ≠ boundary[1] → not empty; *x = 7, top[1] = 3.

/* stack i: boundary[i]+1 .. boundary[i+1] */
bool push(int i, int x) {
  if (top[i] == boundary[i+1]) return false; /* full */
  memory[++top[i]] = x;
  return true;
}
bool pop(int i, int *x) {
  if (top[i] == boundary[i]) return false; /* empty */
  *x = memory[top[i]--];
  return true;
}

Multiple Stacks

Sharing Memory Among n Stacks: Pros and Cons

A one-dimensional array (memory[MEMORY_SIZE]) can be split into n segments to hold n stacks; each stack's top and boundary values are kept in two auxiliary arrays.

Pros

  • One malloc, one array: easy to manage.
  • push/pop are still O(1).
  • The same idea works for queues (n queues).

Cons

  • When one segment fills, you get a “full” error even if memory has room elsewhere.
  • Shifting stacks to make room costs O(m): shifting is expensive.
  • Segment sizes are hard to predict in advance.
Horowitz–Sahni's fix: stack_full(i) looks for free space first to the right, then to the left, and shifts the stacks in between by one cell. In the worst case every push can cost O(m).

Lab · C code step by step

Lab: Linked Stack

Summary

Which Output Orders Are Possible?

We push 1, 2, 3, 4 in this order and may pop any number of times in between. Which of the output orders below can we get?

Output orderPossible?
1 2 3 4
showYes: pop right after each push.
4 3 2 1
showYes: four pushes, then four pops.
2 4 3 1
showYes: push1 push2 pop(2) push3 push4 pop(4) pop(3) pop(1).
3 1 4 2
showNo: when 3 comes out, 1 and 2 are on the stack with 2 on top, so 1 cannot come out before 2.

General rule: after some x is output, the items pushed before x and not yet popped must come out in reverse order. The number of possible orders for n items is a Catalan number (14 for n = 4).

Summary

Complexity Summary

OperationFixed arrayGrowable arrayLinked
pushO(1)O(1) amortized, O(n) worst caseO(1)
popO(1)O(1)O(1)
peek / empty / fullO(1)O(1)O(1)
Memory for n itemsMAX (fixed)≤ 2nn · (item + pointer)
CleanupO(1)O(1) (one free)O(n)
fact(n) call stackO(n) frames (whatever the implementation)
Multiple-stack pushO(1); making room O(m)——

Summary

Common Mistakes

1Popping an empty stack or pushing onto a full one: skipping the bounds check.
2Writing *top--: it decrements the pointer; the correct form is (*top)--.
3Confusing the value of top with the item count (count = top + 1).
4In a linked push, writing *top = new_node first and losing the old list.
5In pop, reading the value after free, or never freeing the node.
6Calling malloc for a temporary pointer that doesn't need it, and leaking memory.

Summary

Exercises

  1. Make the array stack's push return bool instead of calling exit.
  2. Write push(k, x) and pop(k) for two stacks in one array (k = 1, 2).
  3. Wrap the linked stack in a struct holding top and a size field.
  4. Write void reverse(char *s): reverse a string with a stack.
  5. With only push/pop, return a stack's bottom item (a helper stack is allowed).
  6. At most how many frames are on the stack during fact(5)? Draw them with main.
Hints / answers
  1. On overflow return false;, otherwise stack[++*top] = item; return true;.
  2. Empty: top1 = −1, top2 = m. Full: top1 + 1 == top2. For k = 2, push uses --top2 and pop uses top2++.
  3. typedef struct { node *top; int size; } LinkedStack;; ++size on push, --size on a successful pop.
  4. Push the characters, then pop them back into the array: O(n) time, O(n) extra memory.
  5. Move all to the helper stack, keep the last, move them back: O(n).
  6. fact(5), fact(4), …, fact(1) + main = 6 frames.

Summary

Chapter Summary

LIFO

Insert and delete only at the top; last in, first out.

Array + top

top = −1 empty, top = MAX − 1 full; ++*top and (*top)--.

Error handling

Return a status instead of calling exit; the caller decides about overflow/underflow.

Linked stack

top = head of list; push/pop O(1); free every node you pop.

Call stack

Each call is a frame: return address, locals, previous frame.

Multiple stacks

One memory, top[i] and boundary[i]; a full segment forces shifting.

Summary

References and Next Steps

  • E. Horowitz, S. Sahni, S. Anderson-Freed, Fundamentals of Data Structures in C, 2nd ed., Sections 3.1–3.2, 3.7, and 4.3.
  • T. H. Cormen et al., Introduction to Algorithms, 3rd ed., Section 10.1 (stacks) and Chapter 17 (amortized analysis).
  • R. Sedgewick, Algorithms in C, Parts 1–4, Chapter 4.

The End

Chapter 6: Stacks
Next chapter: Chapter 7: Queues · Course page
1 / 1 Data Structures and Algorithms with C