Chapter 8: Stack and Queue Applications

Data Structures and Algorithms with C
MazeBacktrackingOperator precedenceInfix / postfix / prefixPostfix evaluationBracket matching
Sercan KÜLCÜ · Giresun University · Computer Engineering

Introduction

Learning Outcomes

Code backtracking

Search a maze with a stack and trace how it backs out of dead ends.

Build the worst case

Design and analyze the worst-case input for an algorithm.

Convert notations

Convert among infix, prefix, and postfix by hand and with a stack.

Evaluate postfix

Run eval step by step with its operand stack.

Encode precedence

Write the infix → postfix routine using the isp/icp tables.

Generalize the stack

Use stacks for bracket matching, undo/redo, and non-recursive traversal.

Maze

The Maze Problem

0011223344556677ES

In an m×p matrix, 0s are open paths and 1s are walls. The entrance is [1][1] (S) and the exit [6][6] (E): we want a path from entrance to exit.

  • Moves are horizontal, vertical, and diagonal: 8 directions.
  • To avoid checking “am I leaving the matrix?” at every step, the matrix is surrounded by a border of 1s.
  • Visited cells are marked in the mark matrix, so no cell is entered twice.
  • At a dead end we back up to the most recent fork: last in, first out → a stack.

Maze

Eight Directions and the move[] Table

dirmove[dir].vertmove[dir].horiz
0−10
1−11
201
311
410
51−1
60−1
7−1−1
7[i−1][j−1]0[i−1][j]1[i−1][j+1]6[i][j−1]dir[i][j]2[i][j+1]5[i+1][j−1]4[i+1][j]3[i+1][j+1]

Direction 0 is north; 1…7 go clockwise. New position: [i + vert][j + horiz].

An eight-entry look-up table saves writing eight separate ifs: the direction becomes a loop variable.

Maze

Definitions for the Maze

#define MAX_STACK_SIZE 100
#define EXIT_ROW 6
#define EXIT_COL 6
typedef struct { short int vert, horiz; } offsets;
offsets move[8] = {{-1, 0}, {-1, 1}, {0, 1}, {1, 1},
                   {1, 0}, {1, -1}, {0, -1}, {-1, -1}};
typedef struct { short int row, col, dir; } element;
element stack[MAX_STACK_SIZE];
int top = -1;
short int mark[8][8];
short int maze[8][8] = {{1,1,1,1,1,1,1,1},
    {1,0,1,0,0,0,1,1}, {1,0,1,0,1,1,1,1},
    {1,1,0,1,1,1,1,1}, {1,0,1,1,0,1,1,1},
    {1,1,0,0,1,0,1,1}, {1,1,1,1,1,1,0,1},
    {1,1,1,1,1,1,1,1}};
  • element: the record pushed on the stack: which cell (row, col) and, if we come back, which direction to try next (dir).
  • mark: visited cells (zero at the start because it is global).
  • maze: an 8×8 matrix with a border of 1s; the interior is 6×6.
  • The stack never holds more entries than there are open cells (13 here).

Maze

The path Routine

void path(void) {
  short int row, col, next_row, next_col;
  int i, dir, found = FALSE;
  element position;
  stack[0].row = stack[0].col = 1;
  stack[0].dir = 1;     /* push the start */
  mark[1][1] = 1;  top = 0;
  while (top > -1 && !found) {
    position = pop(&top);     /* next one */
    row = position.row;
    col = position.col;
    dir = position.dir;       /* which way */
    while (dir < 8 && !found) {
      next_row = row + move[dir].vert;
      next_col = col + move[dir].horiz;
      if (next_row == EXIT_ROW &&
          next_col == EXIT_COL)
        found = TRUE;         /* the exit? */
      else if (!maze[next_row][next_col] &&
               !mark[next_row][next_col]) {
        mark[next_row][next_col] = 1;
        position.row = row;   /* came from */
        position.col = col;
        position.dir = ++dir; /* resume dir */
        push(&top, position);
        row = next_row;  col = next_col;
        dir = 0;
      } else ++dir;           /* try another */
    }                         /* back up */
  }

If found, the stack positions (0…top), the last position and the exit are printed; otherwise “The maze does not have a path”. (Lines split for readability; logic unchanged.)

Maze · Run the code step by step

Code Trace: Backtracking with a Stack

0011223344556677E

Start: the stack holds (1,1) dir 1. stack: row,col,dir records (bottom to top).

0011223344556677E

First pop: (1,1), starting at dir 1 (dir 0 is a wall anyway).

0011223344556677ES

From (1,1), dir 4 (S) is open → move to (2,1); (1,1, dir 5) pushed.

0011223344556677ES

From (2,1), dir 3 (SE) is open → move to (3,2); (2,1, dir 4) pushed.

0011223344556677ES

From (3,2), dir 1 (NE) is open → move to (2,3); (3,2, dir 2) pushed.

0011223344556677ES

From (2,3), dir 0 (N) is open → move to (1,3); (2,3, dir 1) pushed.

0011223344556677ES

From (1,3), dir 2 (E) is open → move to (1,4); (1,3, dir 3) pushed.

0011223344556677ES

From (1,4), dir 2 (E) is open → move to (1,5); (1,4, dir 3) pushed.

00×11223344556677ES

Back up / pop: return to (1,4) and keep trying from dir 3 (SE).

00××11223344556677ES

Back up / pop: return to (1,3) and keep trying from dir 3 (SE).

00×××11223344556677ES

Back up / pop: return to (2,3) and keep trying from dir 1 (NE).

00×××11×223344556677ES

Back up / pop: return to (3,2) and keep trying from dir 2 (E).

00×××11×223344556677ES

From (3,2), dir 5 (SW) is open → move to (4,1); (3,2, dir 6) pushed.

00×××11×223344556677ES

From (4,1), dir 3 (SE) is open → move to (5,2); (4,1, dir 4) pushed.

00×××11×223344556677ES

From (5,2), dir 2 (E) is open → move to (5,3); (5,2, dir 3) pushed.

00×××11×223344556677ES

From (5,3), dir 1 (NE) is open → move to (4,4); (5,3, dir 2) pushed.

00×××11×223344556677ES

From (4,4), dir 3 (SE) is open → move to (5,5); (4,4, dir 4) pushed.

00×××11×223344556677ES

Dir 3 (SE) is the exit! Path: the stack + (5,5) + (6,6).

while (top > -1 && !found) {
  position = pop(&top);
  row = position.row;  col = position.col;
  dir = position.dir;
  while (dir < 8 && !found) {
    nr = row + move[dir].vert;
    nc = col + move[dir].horiz;
    if (nr == EXIT_ROW && nc == EXIT_COL)
      found = TRUE;
    else if (!maze[nr][nc] &&
             !mark[nr][nc]) {
      mark[nr][nc] = 1;
      position = (element){row, col, ++dir};
      push(&top, position);
      row = nr;  col = nc;  dir = 0;
    } else ++dir;
} }

Maze

Assessment and the Worst Case

  • The eight-entry look-up table shortened the code and made the job easier.
  • The program does a brute-force search of the maze with a stack.
  • A worst-case analysis needs the worst-case input; the order in which directions are scanned decides it.
  • Input 1: the first path tried is long but correct → only pushes, no pops.
  • Input 2: the first path tried is long and wrong → it is followed to the end and the stack is emptied one by one; the solution is reached only after every cell off the correct path has been visited. This is the worst-case input.
Input 1Input 2
Instructor “Don't turn your nose up at an algorithm when you can't even analyze it!”

Maze

Complexity, and a Comparison with a Queue

Time

Each open cell is pushed at most once (mark), and at most 8 directions are tried per cell: O(m·p) for an m×p maze.

Memory

The stack grows at most to the number of open cells: O(m·p); mark is O(m·p) too.

Stack (DFS)

The path found need not be the shortest. In this maze it went into the (2,3)→(1,3)→(1,4)→(1,5) dead end and came back; the path it found has 9 cells.

Queue (BFS)

Expands cells in order of distance, so it guarantees the shortest path. Here it finds the same 9-cell path, but in general the DFS path can be longer.

Instructor “Only the person who wrote a piece of code can examine it in full detail. Nobody else can analyze it completely.”
Instructor “If there were 30–40 students instead of 120–130, and I had 4–5 assistants, I could go through the assignments in much more detail.”

Expression Notations

Evaluating Expressions

Compilers also use stacks to evaluate logical and arithmetic expressions. How does a compiler cope with expressions like these?

Precedence

x = a / b − c + d * e − a * c

Value

((4 / 2) − 2) + (3 * 3) − (4 * 2) = 1

Parentheses

a / (b − c) + d * (e − a) * c

  • Reading left to right, we can't apply an operator right away: a higher-precedence operator may follow it.
  • The solution has two phases: first convert the expression to postfix according to precedence, then evaluate the postfix in a single pass. Both use a stack.
Instructor “Research the problem first; others have solved it many times. Find the fastest way. Only if it's unsolved does discovery begin.”

Expression Notations

Operator Precedence in C (Summary)

PrecedenceOperatorsAssociativity
highest() [] -> .left to right
unary − ! ++ -- * &right to left
* / %left to right
+ −left to right
< <= > >=left to right
== !=left to right
&&left to right
lowest||left to right
  • Precedence comes first; on a tie, associativity decides: a − b − c = (a − b) − c.
  • Parentheses override everything.
  • Example: a / b − c + d * e − a * c = (((a / b) − c) + (d * e)) − (a * c).
  • The algorithms in this chapter handle only + − * / % and parentheses (Horowitz–Sahni, Figure 3.12).

Expression Notations

Infix, Prefix, Postfix

  • Infix: the operator sits between its operands, a + b. Both parentheses and precedence must be taken into account.
  • Prefix (Polish notation): the operator comes first, + a b.
  • Postfix (reverse Polish): the operator comes last, a b +. Prefix and postfix need no parentheses and are evaluated without thinking about precedence.
#PrefixInfixPostfix
1*343*434*
2+2*342+3*4234*+
3-*+abc/da(a+b)*c-d/aab+c*da/-
4**/a+-bcd-eac(a/(b-c+d))*(e-a)*cabc-d+/ea-*c*

Expression Notations

Converting by Hand: Parenthesize, Move, Erase

a / b − c + d * e − a * c

The starting expression.

((((a / b) − c) + (d * e)) − (a * c))

1. Fully parenthesize by precedence and associativity.

((((a b /) c −) (d e *) +) (a c *) −)

2. Move each operator to the right parenthesis that closes it.

a b / c − d e * + a c * −

3. Erase the parentheses: postfix. (For prefix, move each operator to its left parenthesis: − + − / a b c * d e * a c.)

The order of the operands never changes; only the operators move. That observation is the basis of the stack algorithm: operands go straight to the output, and operators wait on the stack until their turn comes.

Expression Notations

Postfix → Infix: 42/2−33*+42*−

token42/2-33*+42*-stack[0]4[1][2][3]top = 0

4 operand → push.

token42/2-33*+42*-stack[0]4[1]2[2][3]top = 1

2 operand → push.

token42/2-33*+42*-stack[0](4/2)[1][2][3]top = 0

/ operator → pop two (4, 2) and push back (4/2).

token42/2-33*+42*-stack[0](4/2)[1]2[2][3]top = 1

2 operand → push.

token42/2-33*+42*-stack[0]((4/2)-2)[1][2][3]top = 0

- operator → pop two ((4/2), 2) and push back ((4/2)-2).

token42/2-33*+42*-stack[0]((4/2)-2)[1]3[2][3]top = 1

3 operand → push.

token42/2-33*+42*-stack[0]((4/2)-2)[1]3[2]3[3]top = 2

3 operand → push.

token42/2-33*+42*-stack[0]((4/2)-2)[1](3*3)[2][3]top = 1

* operator → pop two (3, 3) and push back (3*3).

token42/2-33*+42*-stack[0](((4/2)-2)+(3*3))[1][2][3]top = 0

+ operator → pop two (((4/2)-2), (3*3)) and push back (((4/2)-2)+(3*3)).

token42/2-33*+42*-stack[0](((4/2)-2)+(3*3))[1]4[2][3]top = 1

4 operand → push.

token42/2-33*+42*-stack[0](((4/2)-2)+(3*3))[1]4[2]2[3]top = 2

2 operand → push.

token42/2-33*+42*-stack[0](((4/2)-2)+(3*3))[1](4*2)[2][3]top = 1

* operator → pop two (4, 2) and push back (4*2).

token42/2-33*+42*-stack[0]((((4/2)-2)+(3*3))-(4*2))[1][2][3]top = 0

- operator → pop two ((((4/2)-2)+(3*3)), (4*2)) and push back ((((4/2)-2)+(3*3))-(4*2)). Result: ((((4/2)−2)+(3*3))−(4*2)).

After the *, cell [1] is not empty: it holds (3*3), then (4*2) (top = 1).

Postfix Evaluation

Tokens: get_token

typedef enum { lparen, rparen, plus, minus,
    times, divide, mod, eos, operand } precedence;

precedence get_token(const char *expr, char *symbol, int *n) {
    *symbol = expr[(*n)++];
    switch (*symbol) {
        case '(':  return lparen;
        case ')':  return rparen;
        case '+':  return plus;
        case '-':  return minus;
        case '/':  return divide;
        case '*':  return times;
        case '%':  return mod;
        case '\0': return eos;
        default:   return operand;
    }
}
  • The expression is read one character at a time; each character is a token.
  • Operands are assumed to be single digits. To turn a digit into a number: symbol − '0'. The ASCII code of '2' is 50 and of '0' is 48: 50 − 48 = 2.
  • The expression ends with '\0' → eos.
  • expr could have been a global array; here it is passed as a parameter.
Instructor “Labeling things with typedef enum { … }; makes our job easier.”

Postfix Evaluation

Postfix Evaluation: eval (Global Version)

float eval(void) {
    char symbol;  precedence token;
    float op1, op2;
    int n = 0, top = -1;
    token = get_token(expr, &symbol, &n);
    while (token != eos) {
        if (token == operand)
            push(&top, symbol - '0');
        else {
            op2 = pop(&top);   /* right operand first */
            op1 = pop(&top);
            push(&top, apply(token, op1, op2));
        }
        token = get_token(expr, &symbol, &n);
    }
    return pop(&top);   /* the one left is the result */
}
  • An operand is pushed; an operator pops two operands, applies itself, and pushes the result.
  • The first one popped is op2 (the right operand): 6 2 − means 6 − 2, not 2 − 6.
  • At the end exactly one item must remain on the stack; otherwise the expression is malformed.
  • apply picks among the five operators with a switch; case mod: (int)op1 % (int)op2, since % doesn't work on floats.

Postfix Evaluation

From Globals to Parameters

/* global version: external dependencies */
char expr[] = "42/2-33*+42*-";
float stack[MAX_SIZE];
float eval(void);

The expression and stack are global: you can't evaluate two expressions at once or reuse the routine in another program.

/* component: all parameters/locals */
float eval(const char *expr);
/* the stack is a local array in eval */
/* in main: */
float a = eval("23*54*+9-");
float b = eval("42/2-33*+42*-");

The same routine works anywhere, on any expression, with no side effects. The code traces use this version.

Instructor “Write functions as if you were writing components. Don't create outside dependencies with globals, defines, and the like! That's not how components are written! Tomorrow, working in a team at some company, are you going to tell your project manager: I'm a very special programmer, I have my own style, put my variables above main, that's how I work, take me as I am or else…?”

Postfix Evaluation · Run the code step by step

Code Trace: eval("23*54*+9-")

02132*35445*6+798-stack[0][1][2][3]top = -1

Expression 23*54*+9-; the stack is empty.

02132*35445*6+798-stack[0]2[1][2][3]top = 0

'2' operand: push '2' − '0' = 2.

02132*35445*6+798-stack[0]2[1]3[2][3]top = 1

'3' operand: push '3' − '0' = 3.

02132*35445*6+798-stack[0]6[1][2][3]top = 0

'*' operator: op2 = 3, op1 = 2 → push 2 * 3 = 6.

02132*35445*6+798-stack[0]6[1]5[2][3]top = 1

'5' operand: push '5' − '0' = 5.

02132*35445*6+798-stack[0]6[1]5[2]4[3]top = 2

'4' operand: push '4' − '0' = 4.

02132*35445*6+798-stack[0]6[1]20[2][3]top = 1

'*' operator: op2 = 4, op1 = 5 → push 5 * 4 = 20.

02132*35445*6+798-stack[0]26[1][2][3]top = 0

'+' operator: op2 = 20, op1 = 6 → push 6 + 20 = 26.

02132*35445*6+798-stack[0]26[1]9[2][3]top = 1

'9' operand: push '9' − '0' = 9.

02132*35445*6+798-stack[0]17[1][2][3]top = 0

'-' operator: op2 = 9, op1 = 26 → push 26 - 9 = 17.

02132*35445*6+798-stack[0]17[1][2][3]top = 0

'\0': the loop ends and the one item on the stack, 17, is returned. Each token is handled once → O(n).

float eval(const char *expr) {
  float y[MAX_SIZE], op1, op2;  int top = -1;
  for (int n = 0; expr[n] != '\0'; n++) {
    char c = expr[n];
    if (isdigit(c)) y[++top] = c - '0';
    else {
      op2 = y[top--];  op1 = y[top--];
      switch (c) {
        case '+': y[++top] = op1 + op2; break;
        case '-': y[++top] = op1 - op2; break;
        case '*': y[++top] = op1 * op2; break;
        case '/': y[++top] = op1 / op2; break;
      }
    }
  }
  return y[top];
}

Postfix Evaluation · Run the code step by step

Code Trace: Another Expression

04122/324-53637*8+9410211*12-stack[0][1][2][3]top = -1

Expression 42/2-33*+42*-; the stack is empty.

04122/324-53637*8+9410211*12-stack[0]4[1][2][3]top = 0

'4' operand: push '4' − '0' = 4.

04122/324-53637*8+9410211*12-stack[0]4[1]2[2][3]top = 1

'2' operand: push '2' − '0' = 2.

04122/324-53637*8+9410211*12-stack[0]2[1][2][3]top = 0

'/' operator: op2 = 2, op1 = 4 → push 4 / 2 = 2.

04122/324-53637*8+9410211*12-stack[0]2[1]2[2][3]top = 1

'2' operand: push '2' − '0' = 2.

04122/324-53637*8+9410211*12-stack[0]0[1][2][3]top = 0

'-' operator: op2 = 2, op1 = 2 → push 2 - 2 = 0.

04122/324-53637*8+9410211*12-stack[0]0[1]3[2][3]top = 1

'3' operand: push '3' − '0' = 3.

04122/324-53637*8+9410211*12-stack[0]0[1]3[2]3[3]top = 2

'3' operand: push '3' − '0' = 3.

04122/324-53637*8+9410211*12-stack[0]0[1]9[2][3]top = 1

'*' operator: op2 = 3, op1 = 3 → push 3 * 3 = 9.

04122/324-53637*8+9410211*12-stack[0]9[1][2][3]top = 0

'+' operator: op2 = 9, op1 = 0 → push 0 + 9 = 9.

04122/324-53637*8+9410211*12-stack[0]9[1]4[2][3]top = 1

'4' operand: push '4' − '0' = 4.

04122/324-53637*8+9410211*12-stack[0]9[1]4[2]2[3]top = 2

'2' operand: push '2' − '0' = 2.

04122/324-53637*8+9410211*12-stack[0]9[1]8[2][3]top = 1

'*' operator: op2 = 2, op1 = 4 → push 4 * 2 = 8.

04122/324-53637*8+9410211*12-stack[0]1[1][2][3]top = 0

'-' operator: op2 = 8, op1 = 9 → push 9 - 8 = 1.

04122/324-53637*8+9410211*12-stack[0]1[1][2][3]top = 0

'\0': the loop ends and the one item on the stack, 1, is returned. Each token is handled once → O(n).

float eval(const char *expr) {
  float y[MAX_SIZE], op1, op2;  int top = -1;
  for (int n = 0; expr[n] != '\0'; n++) {
    char c = expr[n];
    if (isdigit(c)) y[++top] = c - '0';
    else {
      op2 = y[top--];  op1 = y[top--];
      switch (c) {
        case '+': y[++top] = op1 + op2; break;
        case '-': y[++top] = op1 - op2; break;
        case '*': y[++top] = op1 * op2; break;
        case '/': y[++top] = op1 / op2; break;
      }
    }
  }
  return y[top];
}

Infix → Postfix

Infix → Postfix: the Algorithm

  • Operand: written straight to the output.
  • Operator: while the operator on the stack has precedence greater than or equal to the incoming one, pop it to the output; then push the incoming operator (popping on ties = left associativity).
  • ( : always pushed; once inside the stack it acts as the lowest precedence.
  • ): pop to the output until ( is seen; discard the (.
  • At the end: pop everything left on the stack to the output.
Tokenisp (in stack)icp (incoming)
(020
* / %1313
+ −1212
# (bottom marker)−1—
( has two precedences: highest when arriving (it goes in without popping anything) and lowest on the stack (any operator can sit on top of it). The # at the bottom of the stack stops the loop.

Infix → Postfix · Run the code step by step

Code Trace: a*(b+c)-d → Postfix

0a1*2(3b4+5c6)7-8dstack[0][1][2][3]top = -1

Expression a*(b+c)-d. A # (isp = −1) sits at the bottom of the stack; it is not drawn.

0a1*2(3b4+5c6)7-8dstack[0][1][2][3]top = -1

a operand → output.

0a1*2(3b4+5c6)7-8dstack[0]*[1][2][3]top = 0

*: isp(#) = -1 < icp(*) = 13 → push *.

0a1*2(3b4+5c6)7-8dstack[0]*[1]([2][3]top = 1

(: isp(*) = 13 < icp(() = 20 → push (.

0a1*2(3b4+5c6)7-8dstack[0]*[1]([2][3]top = 1

b operand → output.

0a1*2(3b4+5c6)7-8dstack[0]*[1]([2]+[3]top = 2

+: isp(() = 0 < icp(+) = 12 → push +.

0a1*2(3b4+5c6)7-8dstack[0]*[1]([2]+[3]top = 2

c operand → output.

0a1*2(3b4+5c6)7-8dstack[0]*[1][2][3]top = 0

): pop until ( → + to output; ( discarded.

0a1*2(3b4+5c6)7-8dstack[0]-[1][2][3]top = 0

-: isp(*) = 13 ≥ icp(-) = 12 → * to output; push -.

0a1*2(3b4+5c6)7-8dstack[0]-[1][2][3]top = 0

d operand → output.

0a1*2(3b4+5c6)7-8dstack[0][1][2][3]top = -1

End of input: the remaining - goes to the output. Result: abc+*d-. Each token is pushed and popped at most once → O(n).

void postfix(const char *e, char *out) {
  char y[MAX] = {'#'};  int top = 0, k = 0;
  for (; *e; e++) {
    if (isalnum(*e)) out[k++] = *e;
    else if (*e == ')') {
      while (y[top] != '(')
        out[k++] = y[top--];
      top--;                /* drop '(' */
    } else {
      while (isp(y[top]) >= icp(*e))
        out[k++] = y[top--];
      y[++top] = *e;
    }
  }
  while (top > 0) out[k++] = y[top--];
  out[k] = '\0';
}

Infix → Postfix · Run the code step by step

Code Trace: the a*(b+c)*d Example

0a1*2(3b4+5c6)7*8dstack[0][1][2][3]top = -1

Expression a*(b+c)*d. A # (isp = −1) sits at the bottom of the stack; it is not drawn.

0a1*2(3b4+5c6)7*8dstack[0][1][2][3]top = -1

a operand → output.

0a1*2(3b4+5c6)7*8dstack[0]*[1][2][3]top = 0

*: isp(#) = -1 < icp(*) = 13 → push *.

0a1*2(3b4+5c6)7*8dstack[0]*[1]([2][3]top = 1

(: isp(*) = 13 < icp(() = 20 → push (.

0a1*2(3b4+5c6)7*8dstack[0]*[1]([2][3]top = 1

b operand → output.

0a1*2(3b4+5c6)7*8dstack[0]*[1]([2]+[3]top = 2

+: isp(() = 0 < icp(+) = 12 → push +.

0a1*2(3b4+5c6)7*8dstack[0]*[1]([2]+[3]top = 2

c operand → output.

0a1*2(3b4+5c6)7*8dstack[0]*[1][2][3]top = 0

): pop until ( → + to output; ( discarded.

0a1*2(3b4+5c6)7*8dstack[0]*[1][2][3]top = 0

*: isp(*) = 13 ≥ icp(*) = 13 → * to output; push *.

0a1*2(3b4+5c6)7*8dstack[0]*[1][2][3]top = 0

d operand → output.

0a1*2(3b4+5c6)7*8dstack[0][1][2][3]top = -1

End of input: the remaining * goes to the output. Result: abc+*d*. Each token is pushed and popped at most once → O(n).

void postfix(const char *e, char *out) {
  char y[MAX] = {'#'};  int top = 0, k = 0;
  for (; *e; e++) {
    if (isalnum(*e)) out[k++] = *e;
    else if (*e == ')') {
      while (y[top] != '(')
        out[k++] = y[top--];
      top--;                /* drop '(' */
    } else {
      while (isp(y[top]) >= icp(*e))
        out[k++] = y[top--];
      y[++top] = *e;
    }
  }
  while (top > 0) out[k++] = y[top--];
  out[k] = '\0';
}

Infix → Postfix

Trace Table: a+b*c → abc*+

token[0][1]topOutput
a−1a
++0a
b+0ab
*+*1ab
c+*1abc
eos−1abc*+
  • When * arrives, + is on top: isp(+) = 12 < icp(*) = 13 → * goes on top of it.
  • At the end * comes out first, then +: the higher-precedence operator is applied first.
A common question: “Doesn't the last operand get lost?” No: postfix writes operands to the output immediately and empties the stack at the end, so the last operand is printed too.

Infix → Postfix

Infix → Prefix: Reverse, Postfix, Reverse

(a+b)*c-d/a

One way to get infix → prefix: reverse the expression.

a/d-c*)b+a(

Reversed. Now swap ( and ).

a/d-c*(b+a)

Parentheses fixed. Convert this to postfix, but don't pop on equal precedence (use >), because reversing the expression also reverses associativity.

ad/cba+*-

The postfix result.

-*+abc/da

Reverse it again: prefix. Same as row 3 of the table.

A direct way: scan the expression right to left; operands are prepended to the output, and operators follow the same stack rule. Both ways are O(n).

Infix → Postfix · Run the code step by step

Code Trace: Prefix Evaluation (-+*23*549)

0-1+2*32435*657489stack[0][1][2][3]top = -1

Prefix -+*23*549 (infix: 2*3+5*4−9). Scanned right to left.

0-1+2*32435*657489stack[0]9[1][2][3]top = 0

'9' operand → push.

0-1+2*32435*657489stack[0]9[1]4[2][3]top = 1

'4' operand → push.

0-1+2*32435*657489stack[0]9[1]4[2]5[3]top = 2

'5' operand → push.

0-1+2*32435*657489stack[0]9[1]20[2][3]top = 1

'*': the first popped is op1 = 5 (the left operand!), op2 = 4 → 5 * 4 = 20.

0-1+2*32435*657489stack[0]9[1]20[2]3[3]top = 2

'3' operand → push.

0-1+2*32435*657489stack[0]9[1]20[2]3[3]2top = 3

'2' operand → push.

0-1+2*32435*657489stack[0]9[1]20[2]6[3]top = 2

'*': the first popped is op1 = 2 (the left operand!), op2 = 3 → 2 * 3 = 6.

0-1+2*32435*657489stack[0]9[1]26[2][3]top = 1

'+': the first popped is op1 = 6 (the left operand!), op2 = 20 → 6 + 20 = 26.

0-1+2*32435*657489stack[0]17[1][2][3]top = 0

'-': the first popped is op1 = 26 (the left operand!), op2 = 9 → 26 - 9 = 17.

0-1+2*32435*657489stack[0]17[1][2][3]top = 0

Result 17: the same expression as the postfix example (23*54*+9−). In postfix the first pop was the right operand; in prefix it is the left one.

float prefix_eval(const char *e) {
  float y[MAX], op1, op2;  int top = -1;
  for (int i = strlen(e) - 1; i >= 0; i--) {
    if (isdigit(e[i])) y[++top] = e[i] - '0';
    else {
      op1 = y[top--];  op2 = y[top--];
      y[++top] = apply(e[i], op1, op2);
    }
  }
  return y[top];
}

Infix → Postfix

Exercise: the Other Conversions

in-fixpost-fixpre-fixeval✓?✓???✓✓

✓: done in this chapter · ?: conversions left to design.

EXERCISE: Design the remaining conversion and evaluation algorithms for expression parsing.

  • postfix → infix (done by hand in this chapter; write it in C)
  • postfix → prefix and prefix → postfix
  • infix → prefix (directly, scanning right to left)
  • prefix → infix
  • evaluating infix directly (two stacks: operands and operators)

Other Applications · Run the code step by step

Code Trace: Balanced Brackets {a*(b+c)-[d]}

0{1a2*3(4b5+6c7)8-9[10d11]12}stack[0][1][2][3]top = -1

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

0{1a2*3(4b5+6c7)8-9[10d11]12}stack[0]{[1][2][3]top = 0

{ opens → push.

0{1a2*3(4b5+6c7)8-9[10d11]12}stack[0]{[1][2][3]top = 0

'a' is not a bracket; skip it.

0{1a2*3(4b5+6c7)8-9[10d11]12}stack[0]{[1][2][3]top = 0

'*' is not a bracket; skip it.

0{1a2*3(4b5+6c7)8-9[10d11]12}stack[0]{[1]([2][3]top = 1

( opens → push.

0{1a2*3(4b5+6c7)8-9[10d11]12}stack[0]{[1]([2][3]top = 1

'b' is not a bracket; skip it.

0{1a2*3(4b5+6c7)8-9[10d11]12}stack[0]{[1]([2][3]top = 1

'+' is not a bracket; skip it.

0{1a2*3(4b5+6c7)8-9[10d11]12}stack[0]{[1]([2][3]top = 1

'c' is not a bracket; skip it.

0{1a2*3(4b5+6c7)8-9[10d11]12}stack[0]{[1][2][3]top = 0

) closes and matches the ( on top → pop.

0{1a2*3(4b5+6c7)8-9[10d11]12}stack[0]{[1][2][3]top = 0

'-' is not a bracket; skip it.

0{1a2*3(4b5+6c7)8-9[10d11]12}stack[0]{[1][[2][3]top = 1

[ opens → push.

0{1a2*3(4b5+6c7)8-9[10d11]12}stack[0]{[1][[2][3]top = 1

'd' is not a bracket; skip it.

0{1a2*3(4b5+6c7)8-9[10d11]12}stack[0]{[1][2][3]top = 0

] closes and matches the [ on top → pop.

0{1a2*3(4b5+6c7)8-9[10d11]12}stack[0][1][2][3]top = -1

} closes and matches the { on top → pop.

0{1a2*3(4b5+6c7)8-9[10d11]12}stack[0][1][2][3]top = -1

End of input and the stack is empty → true: balanced.

bool balanced(const char *e) {
  char y[MAX];  int top = -1;
  for (; *e; e++) {
    if (*e=='(' || *e=='[' || *e=='{')
      y[++top] = *e;
    else if (*e==')' || *e==']' || *e=='}') {
      if (top < 0 || !matches(y[top], *e))
        return false;  /* extra/wrong */
      top--;
    }
  }
  return top == -1;       /* none left open? */
}

Other Applications

Bracket Matching: Three Kinds of Error

InputWhat happens?Error
[(a+b]*c)] arrives with ( on topMismatch
(a+b))The stack is empty when the second ) arrivesExtra closer
((a+b)( is left on the stack at the endUnclosed opener
  • A counter is enough for a single kind of bracket; with several kinds you need to know “the most recently opened” → a stack.
  • Compilers, HTML/XML validators, and the matching-bracket highlighting in editors all use this algorithm.
  • Time O(n); memory O(n) in the worst case (all openers).

Other Applications

More Applications of Stacks and Queues

Undo / redo

Two stacks: each action goes on the undo stack, each undone action on the redo stack; a browser's back/forward buttons work the same way.

Non-recursive traversal

Inorder traversal becomes a loop with an explicit stack of node addresses: O(n) time, O(h) stack.

Next greater element

The first larger element to the right of each item, in one pass: a decreasing stack, O(n).

Sliding-window maximum

A deque finds the maximum of every window in O(n).

Shortest path with BFS

Use a queue in the maze and the first path found is a shortest one.

Hanoi, n-queens, sudoku

Recursive backtracking, or backtracking with an explicit stack.

Lab · C code step by step

Lab: Postfix Evaluation

Lab · C code step by step

Lab: Infix → Postfix

Summary

Complexity Summary

AlgorithmStructureTimeExtra memory
Maze (path)stackO(m·p)O(m·p)
Maze shortest pathqueueO(m·p)O(m·p)
Postfix / prefix evaluationstackO(n)O(n)
Infix → postfix / prefixstackO(n)O(n)
Bracket matchingstackO(n)O(n)
Non-recursive inorderstackO(n)O(h)
Level-order traversalqueueO(n)O(n)

n: expression length or number of nodes · m×p: maze size · h: tree height.

Summary

Common Mistakes

1Swapping op1 and op2 in postfix: 6 2 − becomes −4.
2Using the postfix order in prefix: there the first pop is the left operand.
3Not popping on equal precedence in infix → postfix: a−b−c converts wrongly.
4When ) arrives, leaving the ( on the stack or writing it to the output.
5Forgetting the mark in the maze and looping forever.
6Running off the array because the maze has no border of 1s.

Summary

Exercises

  1. Convert a/(b-c)+d*(e-a)*c to postfix and prefix.
  2. Evaluate the postfix expression 6 2 3 + − 3 8 2 / + *.
  3. Write a C routine that converts postfix to infix.
  4. Make path mark the path it finds in the maze.
  5. Find the shortest path through the maze with a queue.
  6. Write non-recursive preorder and postorder traversals.
Hints / answers
  1. Postfix: abc-/dea-*c*+; prefix: +/a-bc**d-eac.
  2. 2+3=5, 6−5=1, 8/2=4, 3+4=7, 1*7 = 7.
  3. Operand: push a one-character string; operator: b = pop, a = pop, push "(" a op b ")". Watch your malloc/free.
  4. Once found, set maze[r][c] = 2 for every (row, col) pair on the stack.
  5. Enqueue (row, col); for each cell remember the cell it came from; on reaching the exit, trace back.
  6. Preorder: push the root; loop: pop, print, push the right child and then the left. Postorder: two stacks or a visited flag.

Summary

Chapter Summary

Backtracking

Every fork in the maze goes on the stack; at a dead end, pop back to the last fork.

Worst case

A long, wrong first path: the whole wrong region gets explored.

Notations

Infix needs precedence; postfix/prefix are evaluated without parentheses or precedence.

Postfix evaluation

Push operands; on an operator pop op2, then op1; push the result. O(n).

Infix → postfix

Pop while isp ≥ icp; ( is high when arriving, low on the stack.

General principle

Wherever you see “last opened, first closed,” use a stack; wherever you see “in order,” use a queue.

Instructor “When I lay your assignment over mine and hold them up to the light… (I'd better not see a difference.)”

Summary

References and Next Steps

  • E. Horowitz, S. Sahni, S. Anderson-Freed, Fundamentals of Data Structures in C, 2nd ed., Sections 3.5 (mazes) and 3.6 (evaluation of expressions).
  • R. Sedgewick, Algorithms in C, Parts 1–4, Sections 4.3 (postfix) and Chapter 5 (recursion and stacks).

The End

Chapter 8: Stack and Queue Applications
Next chapter: Chapter 9: The List ADT and Generalized Lists · Course page
1 / 1 Data Structures and Algorithms with C