Chapter 8: Stack and Queue Applications
Multiple Choice · Maze
Question 1: The Move Table
Directions are numbered clockwise with direction 0 being north: move[5] = {1, -1} (vertical, horizontal). From cell (3, 4), which cell does direction 5 lead to, and what is the direction called?
C: New position [row + vert][col + horiz] = [3 + 1][4 − 1] = (4, 3). Vertical +1 means one row down (south), horizontal −1 one column left (west). Direction 1 is northeast, 3 southeast, 7 northwest.
Step-by-Step Trace · Maze
Question 2: path in a Small Maze
In a 6×6 maze surrounded by 1s, the entrance is (1, 1) and the exit (4, 4). Which route does path find, and where does it backtrack?
The stack holds (row, col, dir) = (1, 1, 1); mark[1][1] = 1. The exit is (4, 4).
pop: continue from (1, 1) with direction 1.
Direction 1 (0, 2) is a wall; direction 2 (E) (1, 2) is open. Push (1, 1, 3) so that on return we continue from direction 3.
From (1, 2) directions 0–3 are walls; direction 4 (S) (2, 2) is open → push (1, 2, 5).
From (2, 2) direction 0 is already marked, 1 and 2 are walls; direction 3 (SE) (3, 3) is open → push (2, 2, 4).
From (3, 3) direction 0 is a wall; direction 1 (NE) (2, 4) is open → push (3, 3, 2).
(2, 4) is a dead end: all eight directions are walls or marked, dir becomes 8 and the inner loop ends.
Backtrack: pop returns to (3, 3) and the search resumes from direction 2.
Direction 2 (3, 4) is a wall; direction 3 (SE) (4, 4) is the exit. Path: the three entries on the stack + (3, 3) + the exit.
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; } }
Multiple Choice · Expression Notations
Question 3: From Infix to Postfix
Which is the postfix equivalent of a - b * c / (d + e)?
B: Full parenthesization: (a − ((b * c) / (d + e))). * and / have equal precedence and associate left to right: first b * c, then the division; the subtraction comes last. A does a − b first; C ignores the parentheses; D applies the subtraction before the division.
Classic Question · Expression Notations
Question 4: Prefix and Postfix by Hand
Fully parenthesize a * (b - c) / d + e and write its prefix and postfix forms. What is the value for a = 6, b = 5, c = 2, d = 9, e = 4?
Show answer
Full parenthesization: (((a * (b − c)) / d) + e)
- Operators move to the right closing parenthesis → postfix:
a b c - * d / e + - Operators move to the left opening parenthesis → prefix:
+ / * a - b c d e
Value: 6 · (5 − 2) = 18, 18 / 9 = 2, 2 + 4 = 6. The order of the operands is the same in all three notations (a b c d e); only the positions of the operators change.
Multiple Choice · Expression Notations
Question 5: From Postfix to Infix
Which is the fully parenthesized infix equivalent of the postfix expression a b c * + d -?
D: With a stack: a, b, c are pushed; * → (b * c); + → (a + (b * c)); d is pushed; − → ((a + (b * c)) − d). When an operator arrives, the first value popped is the right operand. A mixes up the order of + and *.
Step-by-Step Trace · Postfix Evaluation
Question 6: eval("84-2*93/+")
How does the operand stack change during the call eval("84-2*93/+"), and which value is returned?
The expression is 84-2*93/+; the stack is empty.
'8' is an operand: '8' − '0' = 8 is pushed.
'4' is an operand: '4' − '0' = 4 is pushed.
'-' is an operator: op1 = 8, op2 = 4 → 8 − 4 = 4 is pushed.
'2' is an operand: '2' − '0' = 2 is pushed.
'*' is an operator: op1 = 4, op2 = 2 → 4 · 2 = 8 is pushed.
'9' is an operand: '9' − '0' = 9 is pushed.
'3' is an operand: '3' − '0' = 3 is pushed.
'/' is an operator: op1 = 9, op2 = 3 → 9 / 3 = 3 is pushed.
'+' is an operator: op1 = 8, op2 = 3 → 8 + 3 = 11 is pushed.
'\0': the loop ends; the only value left on the stack, 11, is returned. The stack held at most 3 values.
float eval(const char *expr) { float y[MAX], 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--]; y[++top] = apply(c, op1, op2); } } /* exactly one item must be left */ return y[top]; }
Multiple Choice · Postfix Evaluation
Question 7: float or int?
If the stack of eval were an int array instead of float, what would eval("72/3*") return? What does the float version from the lectures return?
A: In the int version 7 / 2 is integer division: 3, then 3 · 3 = 9. In the float version 7 / 2 = 3.5, 3.5 · 3 = 10.5 (both were verified by running them). D assumes 10.5 is rounded; C assumes the float version truncates too, but integer division (truncation toward zero) happens only in the int version.
Classic Question · Postfix Evaluation
Question 8: Multi-Digit Postfix
The eval from the lectures reads only single-digit operands. Write double eval2(const char *e), which evaluates a postfix expression whose operands are separated by spaces and may have several digits (e.g. "12 3 - 4 *" → 36); it should return NAN when an operand is missing or left over.
Show answer
double eval2(const char *e) { double y[MAX], a, b; int top = -1; while (*e) { if (isspace(*e)) { e++; continue; } if (isdigit(*e)) { double v = 0; while (isdigit(*e)) v = v * 10 + (*e++ - '0'); y[++top] = v; continue; } if (top < 1) return NAN; /* missing operand */ b = y[top--]; a = y[top--]; switch (*e++) { case '+': y[++top] = a + b; break; case '-': y[++top] = a - b; break; case '*': y[++top] = a * b; break; default: y[++top] = a / b; } } return top == 0 ? y[0] : NAN; /* NAN: math.h */ }
The digits are combined into one number with v = v * 10 + digit. Tests: "100 25 / 7 +" → 11; "5 +" and "2 3" → NAN.
Step-by-Step Trace · Infix → Postfix
Question 9: Translating a-b+c*(d-e)
How does the operator stack change during the call postfix("a-b+c*(d-e)", out), and what is the result?
The # (isp = −1) sits at the bottom of the stack; it is what stops the loop.
a is an operand → output.
- : isp(#) = −1 < icp(-) = 12 → push.
b → output.
+ : isp(-) = 12 ≥ icp(+) = 12 → - goes to the output (left associativity); + is pushed.
c → output.
* : isp(+) = 12 < icp(*) = 13 → * goes on top.
( : icp 20 is the highest; it is pushed without popping anything.
d → output.
- : isp(() = 0 < 12 → push; the ( on the stack has the lowest priority.
e → output.
) : pop until ( is seen → - goes to the output; ( is discarded.
Input finished: first *, then + go to the output. Result: ab-cde-*+.
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'; }
Multiple Choice · Infix → Postfix
Question 10: What Does the Incoming Operator Pop?
While translating a + b * c - d, at the moment - is read the stack holds (bottom to top) # + *. Which operators are moved from the stack to the output in this step?
C: isp(*) = 13 ≥ icp(-) = 12 → * is popped; isp(+) = 12 ≥ 12 → + is popped too; the loop stops at isp(#) = −1, and then - is pushed. Popping on equality gives left associativity: (a + b * c) − d. Result abc*+d-.
Classic Question · Infix → Postfix
Question 11: Prefix by Reversing
Convert a - b / c + d to prefix with the method “reverse, convert to postfix, reverse again”. Write the intermediate results; why is > used for equal priority?
Show answer
- Reversal (no parentheses):
d + c / b - a - Convert to postfix, not popping on equal priority (
>):d c b / a - + - Reverse again:
+ - a / b c d
Check: + (− a (/ b c)) d = ((a − (b / c)) + d). In the reversed expression left associativity turns into right associativity; had >= been used, the grouping would wrongly come out like a − (… + d).
Multiple Choice · Infix → Postfix
Question 12: Order in Prefix Evaluation
What does prefix_eval("-/82*13") return? The routine scans the expression from right to left; for an operator, the first value popped is the left operand.
B: Right to left: 3, 1 are pushed; * → 1 · 3 = 3; 2, 8 are pushed; / → op1 = 8, op2 = 2 → 4; − → op1 = 4, op2 = 3 → 1. A (2.75) results from using the postfix order: 2 / 8 = 0.25, 3 − 0.25 = 2.75 (both were run).
Classic Question · Other Applications
Question 13: Parenthesis Checking with a Counter
Which faulty inputs does this version, which uses a single counter instead of a stack, accept as balanced? Give two examples and explain the fix.
bool balanced(const char *e) { int open = 0; for (; *e; e++) { if (*e=='(' || *e=='[' || *e=='{') open++; else if (*e==')' || *e==']' || *e=='}') open--; } return open == 0; }
Show answer
"([)]": the counter goes 1, 2, 1, 0 → true. Yet when ] arrives, ( is on top: a wrong match.")(": the counter goes −1, 0 → true. The closing bracket came before the opening one."(a]"also returns true: the type is never compared.
With a single kind of parenthesis, adding if (--open < 0) return false; is enough. With several kinds the “last opened” information is needed: openers are pushed on a stack and a closer must match the top (balanced from the lectures). All were tested by running them.
Multiple Choice · Other Applications
Question 14: Undo and Redo
An editor uses two stacks: every new action goes onto the “undo” stack and empties the “redo” stack. Starting from empty text, the actions are: type A, type B, type C, undo, undo, type D, redo. What is the text?
A: The two undos move C and B to the redo stack (text A). Typing D is a new action: the redo stack is emptied and the text becomes AD. The last redo has nothing left to do. B assumes the redo stack is not emptied.
Classic Question · Summary
Question 15: Stack or Queue: Path Length
In the maze beside (dark cells are walls) with entrance (1, 1) and exit (4, 4), how many cells would the path have if the same eight directions and the same order were used with a queue-based search (BFS)? Why is the path of path longer? What is the maximum number of records the stack holds in the stack-based search?
Show answer
BFS opens cells in order of distance from the entrance: the neighbor (2, 2) of (1, 1) is opened directly on the diagonal, then (3, 3), then the exit. The path has 4 cells: (1, 1) → (2, 2) → (3, 3) → (4, 4).
path is depth-first: because direction 2 (E) is tried before direction 3 (SE), it first enters (1, 2) and continues from there; its path has 5 cells and it also runs into the dead end (2, 4). The stack held at most 4 records (at the dead end). Both searches take O(m·p) time; only BFS guarantees the shortest path (verified in C).
Multiple Choice · Summary
Question 16: Size of the Operator Stack
When an infix expression of length n is converted to postfix, how many symbols can the operator stack hold at the same time, at most?
D: Each symbol is pushed at most once and popped once: time O(n). But in an input like ((((a + b) … all opening parentheses are on the stack at once; runs of operators with increasing priority (a + b * c …) also pile up. The extra memory is O(n) in the worst case.