4.4Exam Practice
Stack: exam questions and answers
This page is the exam practice for the stack section. University exams ask about stacks in a few recurring ways: tracing a sequence of pushes and pops, saying which pop orders are possible, converting expressions between infix, postfix and prefix, evaluating a postfix expression, and coding the stack operations. Here you get original questions of each kind with step-by-step answers.
- How to trace push and pop sequences and possible pop orders with a table
- How to show infix, postfix and prefix conversions and postfix evaluation with a stack table
- How to code a stack with an array and a linked list, a queue with two stacks, and two stacks in one array
1Tracing and conceptual questions
The questions are original, but their types come from the kinds that show up again and again in published midterm and final exams of universities in Turkey and abroad. Solve each question yourself first, then open the box and compare. When writing a stack, put the bottom on the left and the top on the right: in [4, 2, 6], 6 is on top. The function names in the code are the same as in the array stack and linked-list stack lessons.
Code for the next question (Python, array stack):
s = ArrayStack(5)s.push(4)s.push(9)x = s.pop()s.push(2)s.push(x - 3)y = s.pop()print(x + y)s.push(y // 2)print(s.pop(), s.pop())print(s.peek())1What does the code above print? What is left on the stack when it ends?Midterm · tracing
The output has three lines: 15, 3 2 and 4. When the code ends only 4 is left on the stack. Each pop takes the top element; peek looks at the top without removing it.
| Line | Stack (bottom → top) | Variable or output |
|---|---|---|
push(4), push(9) | [4, 9] | |
x = pop() | [4] | x = 9 |
push(2), push(x - 3) | [4, 2, 6] | |
y = pop() | [4, 2] | y = 6 |
print(x + y) | [4, 2] | 15 |
push(y // 2) | [4, 2, 3] | |
print(pop(), pop()) | [4] | 3 2 |
print(peek()) | [4] | 4 |
Code for the next question (C, array stack, capacity 3):
struct Stack s; // CAPACITY 3int x;create(&s);push(&s, 8); push(&s, 3); push(&s, 6); push(&s, 1);pop(&s, &x); pop(&s, &x);push(&s, 9);pop(&s, &x); pop(&s, &x); pop(&s, &x);2With capacity 3, the calls above are made. Write top and the items array after each call. Which calls return false, and why?Midterm · tracing
push(&s, 1) returns false because the stack is full (overflow), and the last pop returns false because the stack is empty (underflow). When the code ends top is -1, but the items array still holds 8, 9, 6: pop does not erase the element, it only decreases top by one.
| Call | Returns | items[0..2] | top |
|---|---|---|---|
push 8 | true | 8, -, - | 0 |
push 3 | true | 8, 3, - | 1 |
push 6 | true | 8, 3, 6 | 2 |
push 1 | false (full) | 8, 3, 6 | 2 |
pop | true, x = 6 | 8, 3, 6 | 1 |
pop | true, x = 3 | 8, 3, 6 | 0 |
push 9 | true | 8, 9, 6 | 1 |
pop | true, x = 9 | 8, 9, 6 | 0 |
pop | true, x = 8 | 8, 9, 6 | -1 |
pop | false (empty) | 8, 9, 6 | -1 |
The values left in items are no longer part of the stack; the valid elements are only those from 0 to top. See Pop: removing an element.
3What principle does a stack follow? Name three places where computers use a stack.Midterm · concepts
A stack follows the LIFO principle: last in, first out. Insertion and removal happen at one end only, the top.
- Function calls: each call goes on the call stack, and when a function ends, the latest call is removed first.
- Undo and the browser's back button: the latest action or the latest page is undone first.
- Compilers: checking balanced parentheses, converting expressions to postfix and evaluating them (Balanced parentheses).
Backtracking in a maze and depth-first search in a graph also use a stack: at a dead end you go back to the last place you branched off.
2Possible pop order questions
4The values 1, 2, 3, 4, 5 are pushed onto a stack in this order, and a pop may happen at any moment in between. Which of these pop orders are possible? (a) 1 3 2 5 4, (b) 4 2 3 1 5, (c) 3 4 2 1 5, (d) 2 1 5 3 4Midterm · pop orders
(a) and (c) are possible, (b) and (d) are not. Testing an order is simple: if the value to pop is not on top, push up to that value; if something else is on top and the value is somewhere inside the stack, the order is impossible.
| Order | Operations | Result |
|---|---|---|
| (a) 1 3 2 5 4 | push 1, pop 1; push 2, push 3, pop 3, pop 2; push 4, push 5, pop 5, pop 4 | Possible |
| (b) 4 2 3 1 5 | push 1..4, pop 4; stack [1, 2, 3], top is 3, but 2 is wanted | Impossible |
| (c) 3 4 2 1 5 | push 1..3, pop 3; push 4, pop 4; pop 2, pop 1; push 5, pop 5 | Possible |
| (d) 2 1 5 3 4 | push 1, 2, pop 2, pop 1; push 3..5, pop 5; stack [3, 4], top is 4, but 3 is wanted | Impossible |
The general rule: after a value x is popped, the smaller values still waiting on the stack must come out from largest to smallest. In (b), 2 and 3 are waiting after 4, and 2 cannot come out before 3.
5If 1, 2, 3 are pushed in this order and a pop may happen at any moment in between, how many different pop orders can you get? Which order cannot be produced?Midterm · pop orders
Of the 6 arrangements of 3 values, 5 can be produced: 1 2 3, 1 3 2, 2 1 3, 2 3 1 and 3 2 1. The order that cannot be produced is 3 1 2.
Why: for 3 to come out first, 1, 2 and 3 must all have been pushed. After 3 is popped, 2 is on top and 1 is below it; 1 cannot come out before 2.
These counts are the Catalan numbers: there are 14 possible orders for n = 4 and 42 for n = 5. Even when the count is not asked, exams expect you to justify an impossible order the way it is done above, by writing out the contents of the stack.
3Expression conversion and evaluation questions
All of these questions ask for the same table: the symbol read, the stack after the step, and the output so far. Precedence: ^ is highest, then * and /, and + and - are lowest. All operators except ^ are processed left to right; ^ is processed right to left.
6Convert A * ( B + C ) - D / E to postfix using a stack. Show the stack and the output after each symbol.Midterm · infix → postfix
The result is A B C + * D E / -. An operand (letter) goes straight to the output. When an operator arrives, operators on top with higher or equal precedence are moved to the output, then the operator is pushed. ( is pushed; when ) arrives, pop until ( is seen.
| Symbol | Stack (bottom → top) | Output |
|---|---|---|
| A | A | |
| * | * | A |
| ( | * ( | A |
| B | * ( | A B |
| + | * ( + | A B |
| C | * ( + | A B C |
| ) | * | A B C + |
| - | - | A B C + * |
| D | - | A B C + * D |
| / | - / | A B C + * D |
| E | - / | A B C + * D E |
| end | A B C + * D E / - |
When - arrives, the * on top has higher precedence, so it goes out first. When / arrives, the - on top has lower precedence, so / is put on top of it. Details: Converting infix to postfix.
7Convert A + B ^ C ^ D * E to postfix. Keep in mind that ^ is processed right to left.Final · infix → postfix
The result is A B C D ^ ^ E * +. The moment that matters is the second ^: since ^ is processed right to left, the ^ of equal precedence on top is not popped, and the new ^ is pushed on top of it. That way B ^ C ^ D reads as B ^ (C ^ D).
| Symbol | Stack (bottom → top) | Output |
|---|---|---|
| A | A | |
| + | + | A |
| B | + | A B |
| ^ | + ^ | A B |
| C | + ^ | A B C |
| ^ | + ^ ^ | A B C |
| D | + ^ ^ | A B C D |
| * | + * | A B C D ^ ^ |
| E | + * | A B C D ^ ^ E |
| end | A B C D ^ ^ E * + |
When * arrives, both ^ have higher precedence and go out; + is lower and stays. If the same rule were used for - or /, that is, without popping on equal precedence, A - B - C would wrongly become A - (B - C).
8Convert ( A - B ) * ( C + D ) / E to prefix notation.Midterm · infix → prefix
The result is / * - A B + C D E. The safest way by hand is to parenthesize the expression fully and move each operator to the front of its own parentheses.
- Parenthesize fully:
( ( ( A - B ) * ( C + D ) ) / E ).*and/have equal precedence, so they group left to right and*goes first. - Innermost:
( A - B )→- A B,( C + D )→+ C D. - One level up:
( - A B ) * ( + C D )→* - A B + C D. - Outermost:
( * - A B + C D ) / E→/ * - A B + C D E.
To check, plug in numbers: with A = 9, B = 4, C = 1, D = 2, E = 3 the infix expression gives (5 · 3) / 3 = 5. Evaluating the prefix expression right to left also gives 5. You can convert with a stack too: reverse the expression, swap the parentheses, convert to postfix without popping on equal precedence, and reverse the result again.
9Evaluate the postfix expression 6 2 3 + * 8 4 / - with a stack. Show the stack after each symbol.Midterm · postfix evaluation
The result is 28. A number is pushed. When an operator arrives, two pops are made: the first value out is the right operand, the second is the left operand; the result is pushed back.
| Symbol | Operation | Stack (bottom → top) |
|---|---|---|
| 6 | push | 6 |
| 2 | push | 6 2 |
| 3 | push | 6 2 3 |
| + | 2 + 3 = 5 | 6 5 |
| * | 6 * 5 = 30 | 30 |
| 8 | push | 30 8 |
| 4 | push | 30 8 4 |
| / | 8 / 4 = 2 | 30 2 |
| - | 30 - 2 = 28 | 28 |
At the end exactly one value must be left on the stack. If more are left, the expression is missing an operator; if an operator arrives with fewer than two values on the stack, it has one operator too many. Mixing up the operand order at - and / is the most common mistake: it is 8 / 4, not 4 / 8. Details: Evaluating a postfix expression.
10Evaluate the prefix expression - * 3 4 / 8 2 with a stack.Final · prefix evaluation
The result is 8. A prefix expression is read right to left. Unlike postfix, when an operator arrives the first value out is the left operand and the second is the right operand.
| Symbol (right to left) | Operation | Stack (bottom → top) |
|---|---|---|
| 2 | push | 2 |
| 8 | push | 2 8 |
| / | 8 / 2 = 4 | 4 |
| 4 | push | 4 4 |
| 3 | push | 4 4 3 |
| * | 3 * 4 = 12 | 4 12 |
| - | 12 - 4 = 8 | 8 |
Check: in infix the expression is 3 * 4 - 8 / 2, that is 12 - 4 = 8.
11Convert the postfix expression a b c * + d e - / to infix. Do not use unnecessary parentheses.Final · postfix → infix
The result is ( a + b * c ) / ( d - e ). The method is the same as in evaluation, but the stack holds text instead of numbers: when an operator arrives, two pieces of text are popped, joined as ( left operator right ) and pushed back.
| Symbol | Stack (bottom → top) |
|---|---|
| a, b, c | a | b | c |
| * | a | (b * c) |
| + | (a + (b * c)) |
| d, e | (a + (b * c)) | d | e |
| - | (a + (b * c)) | (d - e) |
| / | ((a + (b * c)) / (d - e)) |
From the fully parenthesized result, drop the parentheses that precedence already guarantees: b * c is a multiplication and needs none. a + b * c and d - e must be done before the division, so their parentheses stay.
12Check the balance of { [ ( ) ] ( } and [ ( { } ) ] ( with a stack. Which one is unbalanced, and why?Midterm · balanced parentheses
Both are unbalanced, for different reasons. An opening bracket is pushed. When a closing bracket arrives, the top is popped and it must be an opening bracket of the same kind. When the input ends, the stack must be empty.
| Symbol | First string: stack | Symbol | Second string: stack |
|---|---|---|---|
| { | { | [ | [ |
| [ | { [ | ( | [ ( |
| ( | { [ ( | { | [ ( { |
| ) | { [ | } | [ ( |
| ] | { | ) | [ |
| ( | { ( | ] | empty |
| } | top is ( : mismatch | ( | ( |
In the first string, when } arrives the top is (: a kind mismatch, and the check stops there. In the second string every closing bracket finds its partner, but when the input ends ( is still on the stack: an unclosed bracket. The third kind of error is a closing bracket arriving while the stack is empty, as in ( ) ). See Balanced parentheses.
4Code reading questions
void f(int n) { int items[32]; int top = -1; while (n > 0) { items[++top] = n % 2; n = n / 2; } while (top >= 0) printf("%d", items[top--]);}13What does the function f above do? What does f(13) print?Midterm · code reading
f converts n to binary and prints it; f(13) prints 1101. The remainders are found starting from the lowest digit, and the stack hands them back in reverse, starting from the highest digit.
| n | n % 2 | Stack (bottom → top) |
|---|---|---|
| 13 | 1 | 1 |
| 6 | 0 | 1 0 |
| 3 | 1 | 1 0 1 |
| 1 | 1 | 1 0 1 1 |
| 0 | loop ends |
The pop order is 1, 1, 0, 1; the output is 1101. Note: f(0) prints nothing, because the loop is never entered. Exams may ask about this edge case.
s1, s2 = [], []for i in range(1, 5): s1.append(i)while s1: x = s1.pop() if x % 2 == 0: s2.append(x) else: print(x, end=" ")while s2: print(s2.pop(), end=" ")14What does the code above print?Final · code reading
The output is 3 1 2 4. Values leave s1 in the order 4, 3, 2, 1. Odd values are printed at once; even values go onto s2 and come out of it in reverse order at the end.
- s1 = [1, 2, 3, 4]. 4 comes out, even, s2 = [4].
- 3 comes out, odd,
3is printed. - 2 comes out, even, s2 = [4, 2].
- 1 comes out, odd,
1is printed. - 2 and then 4 come out of s2:
2 4is printed.
The even values are reversed twice (once leaving s1, once leaving s2), so they return to their old order, 2 4. Reversing twice keeps the order; this idea is also the basis of the two-stack queue.
5Code writing questions
15Write the push and pop functions in C for an array stack. On overflow and underflow the function returns false.Midterm · code writing
top is the index of the top element and is -1 for an empty stack. Push first checks for a full stack, then increases top and writes. Pop first checks for an empty stack, then reads the value and decreases top.
#define CAPACITY 5struct Stack { int items[CAPACITY]; int top; }; void create(struct Stack* s) { s->top = -1; }bool isEmpty(struct Stack* s) { return s->top == -1; }bool isFull(struct Stack* s) { return s->top == CAPACITY - 1; } bool push(struct Stack* s, int value) { if (isFull(s)) return false; // overflow s->top++; s->items[s->top] = value; return true;} bool pop(struct Stack* s, int* value) { if (isEmpty(s)) return false; // underflow *value = s->items[s->top]; s->top--; return true;}A common mistake is the wrong order: writing first and increasing afterwards writes to items[-1], since top starts at -1. Both operations take O(1). See Push and Pop.
16Write the push and pop functions in C for a linked-list stack.Midterm · code writing
The top is the first node of the list. Push is insertion at the head, pop is deletion from the head. There is no capacity; push returns false only if malloc fails.
struct Node { int data; struct Node* next; };struct Stack { struct Node* top; }; bool push(struct Stack* s, int value) { struct Node* node = malloc(sizeof(struct Node)); if (node == NULL) return false; // out of memory node->data = value; node->next = s->top; // in front of the old top s->top = node; return true;} bool pop(struct Stack* s, int* value) { if (s->top == NULL) return false; // underflow struct Node* temp = s->top; *value = temp->data; s->top = temp->next; free(temp); return true;}If pop moves top forward without keeping the node's address in temp, the node is lost and you get a memory leak; if it calls free first, it reads a freed node. The function names and signatures are the same as in the array version: code that uses the stack does not know which structure was chosen. See Array or linked list?.
17When a stack is built on a linked list, why is the top placed at the head of the list and not at the end?Midterm · concepts
Because in a singly linked list, inserting at the head and deleting from the head take O(1), while deleting from the end takes O(n). With the top at the end, every pop would have to walk from the front to find the next-to-last node.
| Top | push | pop |
|---|---|---|
| Head of the list | Insert at head: O(1) | Delete from head: O(1) |
| End of the list (head only) | Insert at end: O(n) | Delete from end: O(n) |
| End of the list (head + tail) | Insert at end: O(1) | Delete from end: still O(n) |
Keeping a tail speeds up push but not pop, because there is no link going back from the last node (Deleting from the end).
18Keep two stacks in a single array so that neither overflows while the array has free space. Write push1, push2, pop1 and pop2.Final · code writing
The first stack grows from the left end to the right, the second from the right end to the left. The array is full when the two tops meet. Splitting the array in half is wrong: when one half fills up, it overflows even though the other half has room.
#define SIZE 10struct TwoStacks { int items[SIZE]; int top1; int top2; }; void create(struct TwoStacks* s) { s->top1 = -1; s->top2 = SIZE; } bool push1(struct TwoStacks* s, int value) { if (s->top1 + 1 == s->top2) return false; // no room in the array s->items[++s->top1] = value; // grows left to right return true;} bool push2(struct TwoStacks* s, int value) { if (s->top1 + 1 == s->top2) return false; s->items[--s->top2] = value; // grows right to left return true;} bool pop1(struct TwoStacks* s, int* value) { if (s->top1 == -1) return false; *value = s->items[s->top1--]; return true;} bool pop2(struct TwoStacks* s, int* value) { if (s->top2 == SIZE) return false; *value = s->items[s->top2++]; return true;}When empty, top1 is -1 and top2 is the size of the array. The full condition is top1 + 1 == top2, meaning no free cell is left between them. Every operation takes O(1).
19Write a queue (first in, first out) using two stacks. Explain the cost of enqueue and dequeue.Final · code writing
New items are pushed onto the inbox stack. On dequeue, if outbox is empty, every element of inbox is moved to outbox; moving reverses the order and brings the oldest element to the top.
class TwoStackQueue: def __init__(self): self.inbox = [] # new items go here self.outbox = [] # items leave from here def enqueue(self, value): self.inbox.append(value) def dequeue(self): if not self.outbox: # move only when outbox is empty while self.inbox: self.outbox.append(self.inbox.pop()) if not self.outbox: raise IndexError("queue is empty") return self.outbox.pop()Example: 1, 2, 3 are added; the first dequeue moves all three and returns 1. Then 4 is added and goes to inbox. The next dequeue calls return 2 and 3 from outbox, and when outbox is empty, 4 after it is moved over.
enqueue is O(1). A single dequeue can take O(n), but each element is moved at most once, so n operations cost O(n) in total, and the average (amortized) cost per operation is O(1). Moving while outbox is not empty would break the order.
20Write a Java function that reverses a string using a stack.Midterm · code writing
Push the characters in order, then pop until the stack is empty. The LIFO order reverses the sequence by itself.
static String reverse(String text) { java.util.ArrayDeque<Character> stack = new java.util.ArrayDeque<>(); for (char c : text.toCharArray()) stack.push(c); // put every character on the stack StringBuilder result = new StringBuilder(); while (!stack.isEmpty()) result.append(stack.pop()); // take them back in reverse order return result.toString();}reverse("stack") returns "kcats". For n characters the time and extra memory are O(n). Java also has a java.util.Stack class, but ArrayDeque is recommended for new code; both give the same result.
21Using only stack operations (push, pop, is empty), remove every copy of a given value from a stack; the order of the remaining elements must not change.Final · code writing
You cannot look inside a stack; elements are reached one by one from the top. So the elements are moved to a temporary stack, except the value to remove. Moving them back restores the order.
def remove_all(stack, value): temp = [] while stack: # until the stack is empty x = stack.pop() if x != value: temp.append(x) # keep the others on a temporary stack while temp: stack.append(temp.pop()) # put them back in the old orderIf the stack (bottom → top) is [5, 3, 8, 3, 1] and the value is 3, the temporary stack becomes [1, 8, 5], and moving back gives [5, 8, 1]. The two moves reverse the order twice, so the old order is kept. Time O(n), extra memory O(n).
6Complexity questions
22What is the time complexity of push, pop, peek and is-empty for a stack built on an array and one built on a linked list? How do the two differ in memory?Midterm · complexity
In both structures all four operations take O(1); the difference is in memory and limits.
| Array stack | Linked-list stack | |
|---|---|---|
| push | O(1), if not full | O(1) |
| pop, peek, is empty | O(1) | O(1) |
| Searching for a value | O(n) | O(n) |
| Limit | Capacity fixed up front, can overflow | Grows while memory lasts |
| Extra memory | Unused cells sit empty | One pointer per node |
With a dynamic array that doubles when full, a single push sometimes takes O(n), but its average (amortized) cost stays O(1) (Growing the capacity). Searching is not a stack operation anyway; if you need it, choose another data structure.
7Try it
1, 2, 3 are pushed in this order, and pops may happen in between. Which pop order cannot be produced?
The answer is B. When 3 comes out first, 1 and 2 are on the stack with 2 on top. 1 cannot come out before 2.
Show the answer
The answer is B. When 3 comes out first, 1 and 2 are on the stack with 2 on top. 1 cannot come out before 2.
What is the value of the postfix expression 4 2 - 3 *?
The answer is B. At -, 2 and 4 come out; the second one out is the left operand: 4 - 2 = 2. Then 2 * 3 = 6.
Show the answer
The answer is B. At -, 2 and 4 come out; the second one out is the left operand: 4 - 2 = 2. Then 2 * 3 = 6.
Lessons you mark show up in the curriculum. If you are signed in, they are saved to your account too.