←
Class 12 Computer Science
3. Stack · 3 / 13
⌕
Chapter 3 of 13

3. Stack

10 sections · 8,428 words

Opening

263 words · 1 min read

Big idea: The most recent unfinished task is often the next one that must be completed.

Use a separate practice folder for the programs. Each example is self-contained unless its section says otherwise.

  • Explain last in, first out and recognise stack applications.
  • Implement push, pop and peek with an empty-stack policy.
  • Translate simple infix expressions and evaluate postfix expressions.
  • Trace short stack programs and predict their printed output.

Read the rule, trace the worked example, and try the quick check before reading its answers. When a result surprises you, change one input and explain the difference.

This is an original lesson following the listed syllabus topics. Examples, datasets, questions and diagrams were created for this edition.

Stacks appear in many everyday tools. An Undo button reverses the latest change first. A Back button returns to the page visited most recently. A calculator holds unfinished operations while newer ones complete.

This chapter builds the idea in stages. First the rule and its operations. Then a short Python implementation. Then the notation that calculators use. Each stage reuses the previous one.

Study by tracing. Cover the expected output and predict it first. When a prediction fails, find the first line where your trace diverged. That line holds the lesson.

Complete Python examples have Copy code and an external run link. First predict the output. Run the example, then change one input and explain what changed. The output box shows the expected result; it is not another program.

3.1 INTRODUCTION

724 words · 3 min read

You can put values in a list and still use them in many different ways. A data structure adds a rule for how a program may add, find and remove those values. That rule is often the most important part of the design.

For an undo history, the latest unfinished action matters first. You do not need to search every earlier action each time. You need a structure whose next removal naturally selects the newest remaining action.

  1. Describe which item should be used next.
  2. Name the operations the task needs.
  3. Choose a representation that can carry out those operations clearly.
In simple words: A Python list is an implementation tool. “Stack” describes the access rule you choose to enforce.

An editor remembers recent actions so that Undo can reverse the newest one first.

A data structure organises values together with the operations allowed on them. It answers two questions at once. What values are stored, and what may a program do with them.

A stack is an abstract data type. That phrase means its rules describe behaviour on their own. The rules do not depend on one particular representation.

A Python list can implement those rules. But a bare list is not automatically a stack. The program must obey the stack access rules. Using only one end for adding and removing is what makes the behaviour a stack.

An abstract data type describes permitted operations and their behaviour, independently of any particular implementation.

Write down what this program should print before you read the expected output.

actions = []
actions.append("add shape")
actions.append("move shape")
actions.append("change colour")
print(actions.pop())
print(actions)

Opens in a new tab with the code ready. Click Visualize Execution, then step through the program.

  1. Line 1 creates an empty list. It will be used as a stack.
  2. Lines 2 to 4 append 3 actions in order. The last one added is change colour.
  3. Line 5 pops the top. Undo reverses the most recent action first.
  4. Line 6 shows the two earlier actions still stored. Popping removed only the newest.

Output
change colour
['add shape', 'move shape']

Append a fourth action after line 4. Predict which action the pop now reverses.

The top is the accessible end of the stack. New entries arrive there. Removals also happen there. No other position is used directly.

This discipline fits tasks that must resume in reverse order. An interrupted job waits while a newer one finishes. The newer one completes first. Then the older one resumes.

QuestionStack answerQueue answer
Which entry is served next?The newest remaining entry.The oldest remaining entry.
Which end grows?The top.The rear.
Fits Undo?Yes. Reversal is the goal.No. It would undo the oldest first.

Read the table. Each row asks the same question of both structures. The first row is the decision rule. The second row names the growing end. The third row applies both to Undo. Only the stack reverses in the order Undo needs.

A drawing app records “add shape”, then “move shape”, then “change colour”. Which action should one Undo reverse?

Goal. Choose the action that a single Undo must reverse.

Approach. Ask which recorded action is the most recent unfinished one.

Trace. The three actions arrived in order. Change colour arrived last. Earlier actions remain finished underneath it.

Result. Reverse change colour. The stack order matches that need.

Result: Change colour. A stack matches that order.

Choose the structure from the required behaviour. A queue would favour the oldest pending action. That solves a different problem. A browser Back button and an Undo button both need the newest first.

The same list skills from earlier chapters still apply. Indexing, appending and length all work as before. The stack adds a discipline for using them, not a new container.

Behaviour first, container second. Name the removal order the task needs. Then pick the structure that guarantees it. The familiar list is only an implementation tool.

Common mistake: Do not choose a structure only because its Python container is familiar.

⚡ Quick Check Flashcards3 questions
Question 1
What does abstract data type describe?
Try answering before revealing!
Question 2
Is every use of a list a stack?
Try answering before revealing!
Question 3
Which action does one Undo reverse?
Try answering before revealing!

3.2 STACK

984 words · 4 min read

Imagine a pile where you are allowed to add and remove only the top card. If card C was placed above card B, C must be removed before you can reach B. This is the meaning of last in, first out.

The words last and first refer to arrival and removal, not to a value’s size or spelling. Repeated values can be stored too. Their positions in the history still decide which entry leaves next.

  1. Mark one end as the top.
  2. Place each new item at that end.
  3. Remove from that same end and describe which older item becomes visible.
In simple words: The next pop answers “what was added most recently and is still here?”

Imagine adding cards to the top of a pile and taking cards only from that same top.

A stack follows LIFO: last in, first out. Among entries still present, the newest is removed first. The bottom holds the oldest remaining entry.

Last and first refer to arrival and removal. They do not refer to value size. A stack may hold repeated values. Their positions in the history decide the removal order.

Last in, first out means the most recently added remaining entry leaves next.

Try to predict the printed result first. The trace below explains every line.

tags = []
tags.append("tag A")
tags.append("tag B")
tags.append("tag C")
print(tags.pop())
print(tags)

Opens in a new tab with the code ready. Click Visualize Execution, then step through the program.

  1. Line 1 creates an empty list for the 3 tags.
  2. Lines 2 to 4 append the tags in order. Tag C arrives last and sits on the top.
  3. Line 5 pops the top and prints tag C.
  4. Line 6 shows the two older tags still stored.

Output
tag C
['tag A', 'tag B']

Push "tag D" after line 4. Predict the next two printed lines.

ActionStack from bottom to top
Push tag AA
Push tag BA, B
Push tag CA, B, C
PopA, B; removed C

Read the table. The right column grows only at its right end. That end is the top. The last row removes from that same end. Tag C arrived last and leaves first.

Before running the program, say the output in your own words.

scores = []
scores.append(5)
scores.append(9)
scores.append(5)
print(scores.pop())
print(scores.pop())
print(scores)

Opens in a new tab with the code ready. Click Visualize Execution, then step through the program.

  1. Lines 2 to 4 store 5, then 9, then 5 again. Repeats are allowed.
  2. Line 5 pops the top. The top holds the second 5. Size never decides.
  3. Line 6 pops again. Now 9 leaves, although 5 is smaller.
  4. Line 7 shows 1 entry left: the first 5 at the bottom.

Output
5
9
[5]

Change line 3 to append(2). Predict all three printed lines.

A marks history behaves the same way. The latest mark is corrected first. Earlier marks stay underneath.

Write down what this program should print before you read the expected output.

history = [12, 15, 9]
print(history.pop())
print(history)
print(history[-1])
print(history)

Opens in a new tab with the code ready. Click Visualize Execution, then step through the program.

  1. Line 1 stores three marks with 9 on the top.
  2. Line 2 pops 9. One entry is removed.
  3. Line 3 prints 2 marks still stored.
  4. Line 4 peeks at the top with index -1. It prints 15 without removing it.
  5. Line 5 proves the peek changed nothing.

Output
9
[12, 15]
15
[12, 15]

Append 11 after line 1. Predict the four printed lines.

Stacks support undo histories, reversing a sequence, checking nested delimiters and tracking function calls. A real browser history may need more than one stack to support both Back and Forward.

One stack alone does not explain every feature.

TaskWhy a stack fits
Undo historyThe latest remaining action must be reversed first.
Reversing a sequencePopping replays entries in reverse arrival order.
Nested delimitersThe latest unmatched opener must meet the next closer.
Function callsAn unfinished call resumes after the newest call finishes.

Read the table. Each row names a task and its reason. Undo needs reversal. Reversing needs reverse replay. Delimiters need latest-unmatched matching. Calls need resume-after-newest. One rule explains all four.

Push: add at the topPeek: inspect the topPop: remove the top
All three stack operations refer to the same accessible end.

Read the diagram. All three boxes point at one end. Push grows it. Peek reads it. Pop shrinks it. No box touches the bottom or the middle.

In a call stack, each unfinished call retains information needed to resume. Recursion adds another active call. This differs from an ordinary loop even if both compute the same answer.

A single stack explains one Back button poorly. Back moves to older pages while Forward returns to newer ones. Two stacks cooperate: one remembers where Back can go, and the other where Forward can go.

A pile of plates shows the physical limit. Only the top plate is reachable. The bottom plate waits until every plate above it is removed. Software stacks copy this discipline without the weight.

A pile holds 4, then 7 on top. Pop once, push 4, then pop once. Which two values leave, in order?

Goal. Predict both removals from a short push and pop sequence.

Approach. Track the top after every step. Removal always takes the current top.

Trace. Push 4, push 7. Pop removes 7. Push 4. The top is 4 again. Pop removes 4.

Result. 7 leaves first, then 4. Position decides, not value size.

Result: 7, then 4. The pop takes the current top each time.

Common mistake: LIFO says which remaining entry leaves next; it does not mean the largest value leaves first.

⚡ Quick Check Flashcards3 questions
Question 1
Tags A, B, C are pushed in that order. What does the next pop remove?
Try answering before revealing!
Question 2
Which stack application relies on matching the latest unmatched opening symbol?
Try answering before revealing!
Question 3
Two 5 values and one 9 are stacked. Which value can leave first?
Try answering before revealing!

3.3 OPERATIONS ON STACK

970 words · 4 min read

Peek answers what is at the top. Pop answers the same question and also removes that item. Push adds a new item. Keeping these meanings separate prevents surprising changes when code only intended to look.

An empty stack has no top item. Its interface must say what happens when a caller asks for one. Raising an exception is a clear option because it cannot be mistaken for a normal stored value.

  1. State the expected contents before the operation.
  2. Decide whether the operation changes those contents.
  3. Check the empty case before trying to use a top value.
In simple words: An operation’s contract includes both its returned result and its change to the stored state.

An operation needs a clear contract for normal and exceptional cases.

Every stack operation needs a contract. The contract states the normal result. It also states the change to the contents. And it states the empty-stack behaviour.

OperationMeaningChange to contents
push(x)Add x at the topAdds one entry.
pop()Remove and return the topRemoves one entry.
peek()Return the top without removing itNo change.
is_empty()Report whether there are no entriesNo change.
size()Report the number of entriesNo change.

Read the table. The middle column is the promise. The right column is the effect. Only push and pop change the contents. Peek, is_empty and size only observe.

Peek observes the top. Pop observes and removes it. Push adds to it.

Predict the output before running this complete example.

stack = ["draft", "review"]
print(stack[-1])
print(stack.pop())
print(stack)

Opens in a new tab with the code ready. Click Visualize Execution, then step through the program.

  1. The right-hand end is the stack top.
  2. The first print reads the top without removing it.
  3. Pop returns that same entry and removes it. The last print shows the smaller list.

Output
review
review
['draft']

Insert a third tag using append and predict the next pop.

Line 1 stores two entries with review on the top. Line 2 reads the last item with index -1. That is the peek idea: it prints review and changes nothing.

Line 3 pops the same entry. It prints review again and removes it. Line 4 shows the one remaining entry. The same printed value can hide a different effect. Only the final list exposes whether removal happened.

Try to predict the printed result first. The trace below explains every line.

stack = ["draft", "review"]
print(stack[-1])
print(len(stack))
print(stack)

Opens in a new tab with the code ready. Click Visualize Execution, then step through the program.

  1. Line 1 stores 2 entries.
  2. Line 2 peeks with index -1 and prints review.
  3. Line 3 prints the size 2. Peeking changed nothing.
  4. Line 4 prints both entries. The stack is intact.

Output
review
2
['draft', 'review']

Replace line 2 with print(stack.pop()). Predict all three printed lines.

Removing or peeking when no entry exists is underflow. A fixed-capacity representation may also have overflow when a push exceeds its capacity.

Python lists grow dynamically. A normal list-based stack has no fixed capacity unless your program imposes one.

Memory is still finite.

Never pop or peek without knowing the stack is non-empty. An empty stack has no top to return.

Ask for the top valueIs anything stored?Empty: report underflowPresent: use the topPop only after the check
Deciding safely whether a stack operation may use the top.

Read the diagram. The first box asks for the top. The second box is the only question that matters: is anything stored. An empty stack takes the third path and reports underflow. A non-empty stack takes the fourth path. The last box is the rule: removal happens only after the check.

Before running the program, say the output in your own words.

stack = []
if stack:
    print(stack.pop())
else:
    print("empty: nothing to remove")
stack.append("note 1")
print(stack.pop())

Opens in a new tab with the code ready. Click Visualize Execution, then step through the program.

  1. Line 1 creates an empty stack.
  2. Line 2 tests the stack. An empty list counts as false.
  3. Lines 4 and 5 run instead. They report the empty state clearly.
  4. Line 6 pushes one entry.
  5. Line 7 pops it safely and prints note 1.

Output
empty: nothing to remove
note 1

Remove line 6. Predict both printed lines.

Peek supports decisions without commitment. A program can ask what is on top before choosing an action. The stack stays unchanged while the program thinks.

Pop supports commitment. Once the program acts on the top entry, removal keeps the history honest. Nothing already handled lingers to be handled twice.

The negative index reads the last item. Pop without an index removes that same item. An empty-stack None must be documented. Otherwise it is confused with a stored None entry. Raising an exception avoids that ambiguity.

An empty list is falsy, so the guard reads naturally. Keep the guard beside every pop whose emptiness you cannot prove. Make underflow impossible by construction where you can, and loud where you cannot.

A program calls pop() three times on a two-entry stack. The third call crashes. What is the smallest repair?

Goal. Stop the crash while keeping every valid removal.

Approach. Ask which call meets an empty stack and what should happen there.

Trace. Two pops empty the stack. The third pop has no top, so it raises. A guard before each uncertain pop takes the empty path instead.

Result. Test the stack before popping, and report or skip the empty case deliberately.

Result: Guard each uncertain pop with an emptiness test. Report underflow instead of crashing.

Common mistake: Peek and pop can return the same value, but only pop removes it.

⚡ Quick Check Flashcards3 questions
Question 1
What is underflow?
Try answering before revealing!
Question 2
Does dynamic growth mean unlimited capacity?
Try answering before revealing!
Question 3
What must a guard check before a pop?
Try answering before revealing!

3.4 IMPLEMENTATION OF STACK IN PYTHON

1,288 words · 6 min read

Use the right-hand end of the list as the top. Append places a value there. Pop without an index removes from there. A last-item index lets you inspect the value without removing it.

The stack parameter names the list being changed. A function call does not create a separate stack unless the code explicitly makes one. Follow the object passed into the function, not only the local variable name.

  1. Read the function definitions without executing their bodies yet.
  2. At each call, write down the list before and after the operation.
  3. Compare peek and pop on the same state to see the difference between reading and removal.
In simple words: Small functions keep the access rule visible and make it harder for the rest of the program to remove from the wrong end.

A short implementation is easier to trust when its state changes can be inspected.

Use the end of a Python list as the top. Append performs push. Pop removes the last entry. Indexing at the last position performs peek. One end does everything.

Stack operationList operation at the end
push(x)append(x) adds at the right end.
pop()pop() removes from the right end.
peek()Index -1 reads the right end.
is_empty()The test not stack is true when empty.
size()len(stack) counts the entries.

Read the table. Every row points at the right end of the list. That end is the top. No row touches position 0. This single choice prevents bottom-removal bugs.

Predict the output before running this complete example.

def push(stack, value):
    stack.append(value)

def pop(stack):
    if not stack:
        raise IndexError("empty stack")
    return stack.pop()

def peek(stack):
    if not stack:
        raise IndexError("empty stack")
    return stack[-1]

stack = []
push(stack, 13)
push(stack, 21)
print(peek(stack))
print(pop(stack))
print(len(stack))

Opens in a new tab with the code ready. Click Visualize Execution, then step through the program.

  1. Function definitions describe the operations; their bodies wait until called.
  2. Each push changes the same list object passed as stack.
  3. Peek reads the last item. Pop then removes it. Len observes the state after that removal.

Output
21
21
1

Pop until empty, then attempt one more pop and explain the chosen error.

Lines 1 to 11 define three functions. Definitions alone change nothing. They wait for calls. Each function receives the stack it must change.

Lines 13 and 14 create an empty list and push 13, then 21. The top is now 21. Line 15 peeks and prints 21 without removing it. Line 16 pops and prints 21 again, this time removing it. Line 17 prints 1: only 13 remains.

Definitions wait; calls act. Trace calls in order. The definitions only explain what each call will do.

Push appends at the topPeek reads without changePop removes the topEmpty needs a guard first
One end does all the work: push adds, peek reads, pop removes, and empty needs a guard.

Read the diagram. The boxes follow one working end. The first box grows it. The second box reads it without change. The third box shrinks it. The last box is the precondition for the other three. Read the boxes before tracing any program.

Write down what this program should print before you read the expected output.

stack = []
stack.append("walk 1")
stack.append("walk 2")
print(len(stack))
print(stack.pop())
print(stack.pop())
print(len(stack))

Opens in a new tab with the code ready. Click Visualize Execution, then step through the program.

  1. Line 1 creates an empty stack.
  2. Lines 2 and 3 append two entries. The size is now 2.
  3. Line 4 prints that size.
  4. Line 5 pops walk 2, the most recent entry.
  5. Line 6 pops walk 1, the remaining entry.
  6. Line 7 prints 0. Every entry was removed in reverse order.

Output
2
walk 2
walk 1
0

Append "walk 3" after line 3. Predict all four printed lines.

These functions change the supplied list in place. They do not create an unrelated global stack. Test an initially empty stack, one entry, repeated entries and a pop sequence that empties it.

The marks history from the previous section now uses the same functions. Nothing about the trace changes. Only the spelling of each operation changes.

Try to predict the printed result first. The trace below explains every line.

def push(stack, value):
    stack.append(value)

def pop(stack):
    if not stack:
        raise IndexError("empty stack")
    return stack.pop()

history = []
push(history, 12)
push(history, 15)
print(pop(history))
print(history)

Opens in a new tab with the code ready. Click Visualize Execution, then step through the program.

  1. Lines 1 to 7 define push and pop. Their bodies wait for calls.
  2. Line 9 creates a separate empty history.
  3. Lines 10 and 11 push 12, then 15. The top is 15.
  4. Line 12 pops and prints 15.
  5. Line 13 shows [12]. The function changed the supplied list in place.

Output
15
[12]

Push 9 after line 11. Predict both printed lines.

Brackets must match in reverse order of opening. An opener waits on the stack. A closer must match the latest unmatched opener. This is the delimiter application from section 3.2, now written as code.

Work through the idea with the two texts below. The first nests round and square brackets correctly. The second closes a round opener with a square closer.

Read the next bracketOpener: push it asideCloser on empty: rejectCloser: pop and compareEnd: empty means balanced
How a stack checks brackets: openers wait, closers must match the latest waiter.

Read the diagram. Read one bracket at a time. An opener is pushed aside for later. A closer on an empty stack is rejected at once. Otherwise pop the latest opener and compare. At the end, an empty stack means every opener found its match.

Before running the program, say the output in your own words.

def balanced(text):
    stack = []
    pairs = {")": "(", "]": "[", "}": "{"}
    for ch in text:
        if ch in "([{":
            stack.append(ch)
        elif ch in ")]}":
            if not stack:
                return False
            if stack.pop() != pairs[ch]:
                return False
    return len(stack) == 0

for text in ["(2 + 3) * [4]", "(2 + 3]"]:
    print(text, balanced(text))

Opens in a new tab with the code ready. Click Visualize Execution, then step through the program.

  1. Line 2 creates an empty waiter stack. Line 3 maps each closer to its opener.
  2. Lines 4 to 11 read the text character by character. Openers are pushed. Other characters are ignored.
  3. A closer with an empty stack returns False at once. Otherwise the latest opener is popped and compared.
  4. The first text balances, so 2 texts are tested and the first prints True.
  5. The second text pops ( for the closer ]. They differ, so it prints False.

Output
(2 + 3) * [4] True
(2 + 3] False

Add the text "{(1)}" to the loop. Predict its printed line.

Passing the stack as a parameter makes the affected state explicit. It also allows separate stacks in one program.

Keep all stack operations in small functions so a larger program cannot accidentally remove from another position.

Python list append and end-pop have amortised constant-time behaviour. Copying or scanning the whole list would change that cost. Small functions keep the fast operations visible and the slow mistakes out.

Trust grows through testing. Start with the examples in this section. Then try an empty stack, a one-entry stack and repeated values. Confirm that peek never changes the size.

A program pushes 5, pushes 8, pops once, then peeks. What does each observation print?

Goal. Predict the printed size, the popped value and the peeked value.

Approach. Track the top after every call. Peek and pop report the same top, but only pop removes it.

Trace. Push 5, push 8. The size is 2. Pop removes 8. The top is 5 again. Peek reports 5 and keeps it.

Result. Size 2, popped 8, peeked 5. The final stack still holds 5.

Result: Size 2, popped 8, peeked 5. The peek proves removal happened only once.

Common mistake: Do not use pop(0) for this representation; that removes the bottom.

⚡ Quick Check Flashcards3 questions
Question 1
Why pass stack as a parameter?
Try answering before revealing!
Question 2
What should a test do after removing the last entry?
Try answering before revealing!
Question 3
Why do push, pop and peek all use the same end?
Try answering before revealing!

3.5 NOTATIONS FOR ARITHMETIC EXPRESSIONS

856 words · 4 min read

The expression A + B * C contains two operations. You must know which one happens first before you can obtain a result. Infix notation puts operators between values and uses precedence and parentheses to explain the grouping.

Prefix and postfix describe the same grouped calculation with the operator before or after its operands. The important idea is preserving the calculation’s structure, not rearranging symbols by appearance.

  1. Identify the innermost operation or highest-priority operation.
  2. Treat its result as one value for the next operation.
  3. Write the equivalent expression in the chosen notation without changing that grouping.
In simple words: If a conversion changes which pair is combined first, it changes the calculation.

Arithmetic notation decides where an operator appears relative to its operands.

An operator combines values. Its operands are the values it combines. Notation decides where the operator stands relative to them.

In infix, the operator stands between its operands, as in A + B. In prefix, it stands before them, as in + A B. In postfix, it stands after them, as in A B +. All three can describe the same calculation.

NotationExpression for a sum followed by multiplication
Infix(A + B) * C
Prefix* + A B C
PostfixA B + C *

Read the table. Each row groups the same way: first add A and B, then multiply by C. Only the operator position changes. The grouping is the meaning; the notation is the spelling.

Infix needs precedence and parentheses to show grouping. Prefix and postfix carry the grouping in their order.

In infix, precedence decides which operator binds tighter when parentheses are absent. Multiplication and division outrank addition and subtraction. Parentheses outrank everything inside their own pair.

Operators of equal precedence need associativity: the side from which they group. Ordinary subtraction and division group from the left. Powers group from the right in written mathematics.

Write down what this program should print before you read the expected output.

print(17 - 6 - 2)
print(17 - (6 - 2))

Opens in a new tab with the code ready. Click Visualize Execution, then step through the program.

  1. Line 1 groups from the left. First 17 - 6 gives 11, then 11 - 2 gives 9.
  2. Line 2 forces the right pair first. 6 - 2 gives 4, then 17 - 4 gives 13.
  3. The same three numbers give different answers. Grouping is part of the meaning.

Output
9
13

Change line 1 to print(17 - 6 + 2). Predict the answer.

Try to predict the printed result first. The trace below explains every line.

print(2 + 3 * 4)
print((2 + 3) * 4)

Opens in a new tab with the code ready. Click Visualize Execution, then step through the program.

  1. Line 1 has no parentheses. Multiplication binds tighter, so 3 * 4 gives 12 first. Adding 2 gives 14.
  2. Line 2 fences the addition. 2 + 3 gives 5 first. Multiplying by 4 gives 20.
  3. Parentheses beat precedence. Precedence beats left-to-right reading.

Output
14
20

Change line 1 to print(2 * 3 + 4). Predict the answer.

Explain why A - B - C differs from A - (B - C).

Goal. Show that grouping changes the result for subtraction.

Approach. Evaluate each form with the same values, following its grouping.

Trace. Left grouping evaluates (A - B) before subtracting C. The parentheses force B - C first in the second form.

Result. The two forms combine different pairs first, so they answer different questions.

Result: For A = 17, B = 6 and C = 2, the results are 9 and 13.

InfixPostfixPrefix
A + BA B ++ A B
A + B * CA B C * ++ A * B C

Read the table. The second row keeps multiplication together in every column. Postfix writes the multiply pair before the add. Prefix writes each operator before its own pair. Trace one column at a time and check the grouping matches.

Prefix and postfix describe a well-formed expression without parentheses. The order itself encodes the grouping. That is why computers like them: no precedence table is needed during evaluation.

Computers prefer postfix for evaluation. No precedence table is needed while scanning. No parentheses must be matched either. The order of tokens already records every grouping decision.

Think of an expression as a small tree. Leaves hold operands. Each branch holds one operator with its two children. Postfix lists each branch after its children. This order is why one left-to-right scan suffices.

Some written algebra uses ^ for exponentiation and groups successive powers from the right. Python uses ** for exponentiation. The symbol ^ in Python is a bitwise operator. Keep the notation used by an exercise separate from executable Python syntax.

Work through the idea with numbers, not letters alone. Letters hide grouping mistakes that numbers expose.
Common mistake: Postfix order must preserve the expression tree, not just move all operators to the end.

⚡ Quick Check Flashcards3 questions
Question 1
What is postfix for A + B * C?
Try answering before revealing!
Question 2
Is ^ the Python exponentiation operator?
Try answering before revealing!
Question 3
Which groups first without parentheses: + or *?
Try answering before revealing!

3.6 CONVERSION FROM INFIX TO POSTFIX NOTATION

1,170 words · 5 min read

When converting infix to postfix, an operand can go straight to the result. An operator may need to wait because a higher-priority operation could come next. The operator stack is that waiting area.

Parentheses temporarily fence off a subexpression. When its closing parenthesis arrives, the operators inside that fence can be released. The parentheses themselves do not become postfix operations.

  1. Send operands to the output in their reading order.
  2. Use precedence and associativity to decide when waiting operators can leave the stack.
  3. After all tokens are read, release the remaining valid operators.
In simple words: The operator stack records unfinished grouping decisions. It is not the final arithmetic answer.

An operator stack holds work that cannot be emitted until higher-priority work has been handled.

Conversion reads infix tokens left to right. A token is one meaningful unit: a number, an operator or a parenthesis. The digit pair 12 is one token, not two.

Send each operand directly to the output. Operands never wait. Push an opening parenthesis onto the operator stack. It fences off the subexpression inside it.

On a closing parenthesis, pop operators to the output until the matching opener is reached. Then discard the opener. The parentheses controlled grouping, so they never enter the postfix result.

Before pushing a new left-associative operator, pop any waiting operator with higher or equal precedence. Higher precedence must be emitted first.

Equal precedence must also go first, because left grouping means the earlier operator combines first.

For a right-associative power operator, pop only higher precedence. Equal precedence waits, because the right pair combines first. At the end, pop the remaining operators. Unmatched parentheses indicate invalid input.

The operator stack stores unfinished grouping decisions. It is not the answer.

Input tokenOutput so farOperator stack
((
99(
-9( -
39 3( -
)9 3 -
*9 3 -*
29 3 - 2*
End9 3 - 2 *

Read the table. Follow one row at a time. The opener waits in the third column. Operands pass straight to the middle column. The closer releases the waiting minus and discards the fence. The final row empties the stack into the output.

Read the next tokenOperand: send to outputOperator: settle the waitersCloser: release the fenceEnd: empty the stack
Converting infix to postfix: operands pass through while operators wait their turn.

Read the diagram. The first box reads one token. Operands take the fast path to the output. Waiting operators are settled before a newcomer is pushed. A closer releases everything back to its fence. The last box runs once, after all tokens are read.

Tokens are meaningful units, not individual characters. A multidigit number belongs together. The following compact conversion handles +, -, * and / with binary operators. Unary minus and power require additional rules.

Conversion and evaluation are inverse skills. Conversion records grouping decisions into token order. Evaluation replays that order with a value stack. Learn them as a pair, not as isolated tricks.

Predict the output before running this complete example.

def to_postfix(tokens):
    priority = {"+": 1, "-": 1, "*": 2, "/": 2}
    output, operators = [], []
    for token in tokens:
        if token == "(":
            operators.append(token)
        elif token == ")":
            while operators and operators[-1] != "(":
                output.append(operators.pop())
            if not operators:
                raise ValueError("unmatched parenthesis")
            operators.pop()
        elif token in priority:
            while (operators and operators[-1] != "("
                   and priority[operators[-1]] >= priority[token]):
                output.append(operators.pop())
            operators.append(token)
        else:
            output.append(token)
    if "(" in operators:
        raise ValueError("unmatched parenthesis")
    return output + operators[::-1]

print(" ".join(to_postfix("( 9 - 3 ) * 2".split())))

Opens in a new tab with the code ready. Click Visualize Execution, then step through the program.

  1. An operand can be sent directly to output because it needs no precedence decision.
  2. The operator stack holds operators that must wait for a later operand or higher-priority operation.
  3. A closing parenthesis releases the operators inside its matching opening parenthesis.
  4. At the end, reversing the remaining stack gives its pop order.

Output
9 3 - 2 *

Use an expression with addition and multiplication but no parentheses. Trace why multiplication appears earlier in the postfix result.

The function keeps two lists. Output collects finished postfix tokens. Operators holds the waiting stack. The split call turns the spaced text into tokens.

Trace the call with ( 9 - 3 ) * 2. The opener is pushed. 9 passes through.

Minus waits behind the fence. 3 passes through. The closer releases the minus and discards the fence.

Star is pushed. 2 passes through. The end empties the stack.

The printed line is 9 3 - 2 *.

Before running the program, say the output in your own words.

def to_postfix(tokens):
    priority = {"+": 1, "-": 1, "*": 2, "/": 2}
    output, operators = [], []
    for token in tokens:
        if token == "(":
            operators.append(token)
        elif token == ")":
            while operators and operators[-1] != "(":
                output.append(operators.pop())
            operators.pop()
        elif token in priority:
            while (operators and operators[-1] != "("
                   and priority[operators[-1]] >= priority[token]):
                output.append(operators.pop())
            operators.append(token)
        else:
            output.append(token)
    return output + operators[::-1]

print(" ".join(to_postfix("2 + 3 * 4".split())))

Opens in a new tab with the code ready. Click Visualize Execution, then step through the program.

  1. Line 1 defines the same conversion without the error checks.
  2. 2 passes straight to the output. Plus waits on the empty stack.
  3. 3 passes straight to the output. Star outranks plus, so it is pushed above it.
  4. 4 passes straight to the output. The end pops star, then plus.
  5. The printed line keeps the multiplication grouped: 2 3 4 * +.

Output
2 3 4 * +

Change the input to "2 * 3 + 4". Predict the printed line.

Write down what this program should print before you read the expected output.

def to_postfix(tokens):
    priority = {"+": 1, "-": 1, "*": 2, "/": 2}
    output, operators = [], []
    for token in tokens:
        if token == "(":
            operators.append(token)
        elif token == ")":
            while operators and operators[-1] != "(":
                output.append(operators.pop())
            operators.pop()
        elif token in priority:
            while (operators and operators[-1] != "("
                   and priority[operators[-1]] >= priority[token]):
                output.append(operators.pop())
            operators.append(token)
        else:
            output.append(token)
    return output + operators[::-1]

print(" ".join(to_postfix("10 - 4 - 3".split())))

Opens in a new tab with the code ready. Click Visualize Execution, then step through the program.

  1. 10 passes to the output. Minus waits on the empty stack.
  2. 4 passes to the output. The next minus has equal precedence, so the waiting minus is popped first.
  3. 3 passes to the output. The end empties the stack.
  4. The printed line groups from the left: 10 4 - 3 -. Equal precedence is popped for left associativity.

Output
10 4 - 3 -

Change the input to "10 - 4 + 3". Predict the printed line.

Equal precedence pops for left associativity. The earlier minus must be emitted before the later one. Otherwise the grouping would silently change.

Try to predict the printed result first. The trace below explains every line.

def to_postfix(tokens):
    priority = {"+": 1, "-": 1, "*": 2, "/": 2}
    output, operators = [], []
    for token in tokens:
        if token == "(":
            operators.append(token)
        elif token == ")":
            while operators and operators[-1] != "(":
                output.append(operators.pop())
            if not operators:
                raise ValueError("unmatched parenthesis")
            operators.pop()
        elif token in priority:
            while (operators and operators[-1] != "("
                   and priority[operators[-1]] >= priority[token]):
                output.append(operators.pop())
            operators.append(token)
        else:
            output.append(token)
    if "(" in operators:
        raise ValueError("unmatched parenthesis")
    return output + operators[::-1]

try:
    print(to_postfix("( 9 - 3".split()))
except ValueError as error:
    print("Invalid:", error)

Opens in a new tab with the code ready. Click Visualize Execution, then step through the program.

  1. The call has an opener but no closer.
  2. The fence is never released. At the end the check finds ( still waiting.
  3. The function raises ValueError with its message.
  4. The handler prints the message instead of crashing.

Output
Invalid: unmatched parenthesis

Close the parenthesis in the input. Predict the printed line.

Convert 4 + 2 3 to postfix. Show why the operators leave in the order then +.

Goal. Convert one expression with mixed precedence.

Approach. Send operands through, and pop waiting operators of higher or equal precedence before pushing.

Trace. 4 passes through. Plus waits. 2 passes through. Star outranks plus, so it is pushed. 3 passes through. The end pops star, then plus.

Result. 4 2 3 * +. The multiplication stays grouped.

Result: 4 2 3 * +. Star outranks plus, so it leaves the stack first.

Common mistake: Equal-precedence subtraction must be popped for left associativity.

⚡ Quick Check Flashcards3 questions
Question 1
Why is the opening parenthesis not sent to postfix output?
Try answering before revealing!
Question 2
What does the operator stack contain at the end of a valid completed conversion?
Try answering before revealing!
Question 3
When must a waiting operator leave before a newcomer is pushed?
Try answering before revealing!

3.7 EVALUATION OF POSTFIX EXPRESSION

1,028 words · 5 min read

Postfix puts an operation after its required values. By the time an operator is read, its operands should already be on the value stack. Combining them makes one new value that can be used by a later operator.

The most recently pushed operand is the right-hand one. This is easy to miss because addition can hide the error: swapping its inputs does not change the sum. Subtraction exposes the mistake immediately.

  1. Push each incoming operand value.
  2. For an operator, take the right value and then the left value.
  3. Compute the result, push it back, and check that only one result remains at the end.
In simple words: An operator reduces two available values to one result. The order of those two values matters.

Postfix evaluation delays an operation until its operands have already arrived.

Scan postfix tokens left to right. Push each operand value onto a value stack. Values wait there until an operator needs them.

When a binary operator arrives, pop the right operand first, then the left operand. Compute left operator right and push the result. The fresh result waits for the next operator.

A valid complete expression leaves exactly one value. That value is the answer. More values mean something was never combined. Fewer available values mean an operator arrived too early.

An operator reduces two waiting values to one result. Operand order decides subtraction and division.

Predict the output before running this complete example.

def evaluate(tokens):
    stack = []
    for token in tokens:
        if token in ("+", "-", "*", "/"):
            if len(stack) < 2:
                raise ValueError("missing operand")
            right = stack.pop()
            left = stack.pop()
            if token == "+":
                result = left + right
            elif token == "-":
                result = left - right
            elif token == "*":
                result = left * right
            else:
                result = left / right
            stack.append(result)
        else:
            stack.append(int(token))
    if len(stack) != 1:
        raise ValueError("invalid expression")
    return stack.pop()

print(evaluate("9 3 - 2 *".split()))

Opens in a new tab with the code ready. Click Visualize Execution, then step through the program.

  1. A number token adds a value to the working stack.
  2. An operator removes its right operand first and its left operand second.
  3. The calculation result goes back on the stack, ready for a later operation.
  4. Exactly one final value means all operands have been combined into one result.

Output
12

Use subtraction with unequal operands and deliberately reverse their order to see why the pop order matters.

Trace the call with 9 3 - 2 *. Push 9. Push 3. Minus pops right 3, then left 9, and pushes 6. Push 2. Star pops right 2, then left 6, and pushes 12. One value remains, so it is returned and printed.

TokenValue stack
99
39, 3
-6
26, 2
*12

Read the table. Each row shows the stack after that token. Operands grow the stack. Operators shrink it by one: two values leave, one result enters. The last row holds the single final answer.

Read the next tokenNumber: push its valueOperator: pop right, pop leftPush the fresh resultOne value must remain
Evaluating postfix: values wait on the stack until an operator combines the top two.

Read the diagram. Numbers take the waiting path onto the stack. An operator removes the top two in right-then-left order. The fresh result returns to the stack. The last box is the validity check: exactly one value may remain.

Before running the program, say the output in your own words.

def evaluate(tokens):
    stack = []
    for token in tokens:
        if token in ("+", "-", "*", "/"):
            right = stack.pop()
            left = stack.pop()
            if token == "+":
                result = left + right
            elif token == "-":
                result = left - right
            elif token == "*":
                result = left * right
            else:
                result = left / right
            stack.append(result)
        else:
            stack.append(int(token))
    return stack.pop()

print(evaluate("20 6 -".split()))
print(evaluate("6 20 -".split()))

Opens in a new tab with the code ready. Click Visualize Execution, then step through the program.

  1. The first call pushes 20, then 6. Minus pops right 6 and left 20, giving 14.
  2. The second call pushes 6, then 20. The same operator now pops right 20 and left 6, giving -14.
  3. Addition would hide the swap. Subtraction exposes it at once.

Output
14
-14

Change the operator in both calls to /. Predict both printed lines.

Pop right first, then left. Reversing the order silently negates a subtraction and inverts a division. Write the two pops on separate lines so the order is visible.

Write down what this program should print before you read the expected output.

def evaluate(tokens):
    stack = []
    for token in tokens:
        if token in ("+", "-", "*", "/"):
            if len(stack) < 2:
                raise ValueError("missing operand")
            right = stack.pop()
            left = stack.pop()
            if token == "+":
                result = left + right
            elif token == "-":
                result = left - right
            elif token == "*":
                result = left * right
            else:
                result = left / right
            stack.append(result)
        else:
            stack.append(int(token))
    if len(stack) != 1:
        raise ValueError("invalid expression")
    return stack.pop()

for text in ["4 7", "9 +"]:
    try:
        print(evaluate(text.split()))
    except ValueError as error:
        print("Invalid:", error)

Opens in a new tab with the code ready. Click Visualize Execution, then step through the program.

  1. The text 4 7 pushes two values with no operator. Two values remain, so the final check raises.
  2. The text 9 + needs two operands for one value. The length check raises first.
  3. Each handler line names the exact failure.

Output
Invalid: invalid expression
Invalid: missing operand

Add the text "5 +" to the loop. Predict its printed line.

An operator with too few available values is invalid. Several leftover values also indicate an incomplete expression. Division can raise ZeroDivisionError, so a real calculator must decide how to report that case.

Do not use eval on arbitrary input to avoid implementing these rules. Eval would execute any code hidden in the text. The explicit stack evaluates only the four listed operators on integers.

The whole journey now connects. Infix is converted with an operator stack. Postfix is evaluated with a value stack. Two stacks, two jobs, one answer.

Try to predict the printed result first. The trace below explains every line.

def to_postfix(tokens):
    priority = {"+": 1, "-": 1, "*": 2, "/": 2}
    output, operators = [], []
    for token in tokens:
        if token == "(":
            operators.append(token)
        elif token == ")":
            while operators and operators[-1] != "(":
                output.append(operators.pop())
            operators.pop()
        elif token in priority:
            while (operators and operators[-1] != "("
                   and priority[operators[-1]] >= priority[token]):
                output.append(operators.pop())
            operators.append(token)
        else:
            output.append(token)
    return output + operators[::-1]

def evaluate(tokens):
    stack = []
    for token in tokens:
        if token in ("+", "-", "*", "/"):
            right = stack.pop()
            left = stack.pop()
            if token == "+":
                result = left + right
            elif token == "-":
                result = left - right
            elif token == "*":
                result = left * right
            else:
                result = left / right
            stack.append(result)
        else:
            stack.append(int(token))
    return stack.pop()

tokens = to_postfix("( 9 - 3 ) * 2".split())
print(" ".join(tokens))
print(evaluate(tokens))

Opens in a new tab with the code ready. Click Visualize Execution, then step through the program.

  1. The first function converts the infix tokens to postfix.
  2. The join prints the converted form: 9 3 - 2 *.
  3. The second function evaluates those tokens with a value stack.
  4. The printed answer is 12. One expression, two stack stages.

Output
9 3 - 2 *
12

Change the input to "( 9 + 3 ) * 2". Predict both printed lines.

Evaluate the postfix expression 5 1 2 + 4 * + 3 -. Show every stack state.

Goal. Evaluate a longer postfix expression without losing track.

Approach. Push operands. On each operator, pop right then left, compute, and push back.

Trace. Push 5, 1, 2. Plus gives 3. Push 4. Star gives 12. Plus gives 17. Push 3. Minus gives 14.

Result. One value remains, so the expression is valid and its value is printed.

Result: The value is 14. Each operator shrank the stack by exactly one entry.

Common mistake: Reversing the pop order changes subtraction and division.

⚡ Quick Check Flashcards3 questions
Question 1
What is the value of postfix 18 3 /?
Try answering before revealing!
Question 2
Why is postfix 4 7 invalid as a complete expression?
Try answering before revealing!
Question 3
Which operand must be popped first for a binary operator?
Try answering before revealing!

Summary

163 words · 1 min read

Use these points to test what you can explain without looking back.

  • A stack gives access at one end and follows last in, first out.
  • The newest remaining entry leaves first; size and spelling never decide.
  • Push adds, pop removes, and peek inspects the top without change.
  • Specify underflow and any capacity limit before coding.
  • Guard every uncertain pop with an emptiness test.
  • A list implementation uses append and end-pop at the top end.
  • Brackets match latest-opener-first, using push for openers and pop for closers.
  • Infix needs precedence, associativity and parentheses to fix grouping.
  • Infix conversion uses an operator stack; postfix evaluation uses a value stack.
  • Conversion records grouping; evaluation replays it with a value stack.
  • For a binary operation, pop right before left and require one final result.
  • Trace every program line by line, and change one input to test understanding.
For each algorithm or rule, give an input for which it works and a condition under which it needs extra care.

Exercise

982 words · 4 min read

Work independently. For a program, predict the result before running it. Explain your reasoning as well as giving an answer.

3.1 Tags T1 and T2 are pushed, one pop happens, T3 is pushed, then two pops happen. List the removed tags in order.

3.2 An editor keeps every finished action in a list. Explain why Undo reads that list as a stack.

3.3 A stack API returns None both for an empty peek and for a stored None value. Explain the confusion and give a cleaner policy.

3.4 Predict the full output of this history program, then explain each line.

Before running the program, say the output in your own words.

history = []
history.append(6)
history.append(11)
print(len(history))
print(history.pop())
print(history[-1])
print(history)

Opens in a new tab with the code ready. Click Visualize Execution, then step through the program.

  1. Lines 2 and 3 store two marks. The size is 2.
  2. Line 4 prints that size.
  3. Line 5 pops the top and prints 11.
  4. Line 6 peeks with index -1 and prints 6 without removing it.
  5. Line 7 shows [6]. Only the pop changed the contents.

Output
2
11
6
[6]

Append 4 after line 3 and predict all four printed lines.

3.5 This program should drop the oldest waiting tag, but it drops the newest instead. Name the wrong call and give the repair.

Python
tags = ["tag A", "tag B"]
tags.pop(0)
print(tags)

3.6 Convert (P - Q) / R to postfix.

3.7 Convert P + Q * R to prefix.

3.8 Convert (A + B) * (C - D) to postfix.

3.9 Why is A / B / C converted using left associativity?

3.10 Predict the printed line for this left-grouped conversion.

Write down what this program should print before you read the expected output.

def to_postfix(tokens):
    priority = {"+": 1, "-": 1, "*": 2, "/": 2}
    output, operators = [], []
    for token in tokens:
        if token == "(":
            operators.append(token)
        elif token == ")":
            while operators and operators[-1] != "(":
                output.append(operators.pop())
            operators.pop()
        elif token in priority:
            while (operators and operators[-1] != "("
                   and priority[operators[-1]] >= priority[token]):
                output.append(operators.pop())
            operators.append(token)
        else:
            output.append(token)
    return output + operators[::-1]

print(" ".join(to_postfix("8 - 2 + 1".split())))

Opens in a new tab with the code ready. Click Visualize Execution, then step through the program.

  1. 8 passes to the output. Minus waits.
  2. 2 passes to the output. Plus has equal precedence, so the waiting minus is popped first.
  3. 1 passes to the output. The end empties the stack.

Output
8 2 - 1 +

Change the input to "8 + 2 - 1" and predict the printed line.

3.11 What checks are required when evaluating postfix?

3.12 Predict the value printed by this postfix program.

Try to predict the printed result first. The trace below explains every line.

def evaluate(tokens):
    stack = []
    for token in tokens:
        if token in ("+", "-", "*", "/"):
            right = stack.pop()
            left = stack.pop()
            if token == "+":
                result = left + right
            elif token == "-":
                result = left - right
            elif token == "*":
                result = left * right
            else:
                result = left / right
            stack.append(result)
        else:
            stack.append(int(token))
    return stack.pop()

print(evaluate("5 1 2 + 4 * + 3 -".split()))

Opens in a new tab with the code ready. Click Visualize Execution, then step through the program.

  1. Push 5, 1, 2. Plus pops 2 then 1 and pushes 3.
  2. Push 4. Star pops 4 then 3 and pushes 12.
  3. Plus pops 12 then 5 and pushes 17. Push 3.
  4. Minus pops 3 then 17 and pushes 14.

Output
14

Change the final operator to +. Predict the new printed value.

3.13 This evaluator pops left first and then right. Show the failure on 20 6 - and give the repair.

Python
left = stack.pop()
right = stack.pop()
result = left - right

3.14 Describe how a stack checks parentheses.

3.15 Write a bounded stack with capacity 3 that refuses a fourth push with IndexError("stack is full"). Push 1, 2, 3, then 4 inside try, and print the result.

3.16 Write an undo program for marks: push 12 and 15, undo once, then report the current top or empty.

Answers

3.1 T2, then T3, then T1. The first pop removes T2. T3 arrives next and leaves second. T1 waited longest, so it leaves last.

3.2 Undo must reverse the latest remaining action first. Reading only the top and removing it gives exactly that order.

3.3 The caller cannot tell an empty stack from a stored None. Raising a documented exception for the empty case removes the ambiguity.

3.4 2, then 11, then 6, then [6]. The pop removes the newest mark while the peek only observes.

3.5 No call is wrong for a queue, but this stack uses the list end as its top. pop(0) removes the bottom, which breaks last in, first out. The repair is pop() with no index, which removes the newest tag.

3.6 P Q - R /. The fenced subtraction is emitted before the division.

3.7 + P * Q R. The multiplication stays grouped under its own operator.

3.8 A B + C D - *. Each fenced pair is emitted before the final multiplication.

3.9 It means (A / B) / C, so the earlier division must be emitted before a later equal-precedence division.

3.10 8 2 - 1 +. The earlier operator leaves first, so the grouping stays left to right.

3.11 Enough operands for every operator, acceptable operand values, valid operations, and exactly one final result.

3.12 The printed value is 14. Each operator combines the two newest waiting values in right-then-left order.

3.13 The first pop actually holds the right operand 6, but the code names it left. The result is 6 - 20 instead of 20 - 6. The repair pops right first, then left, and computes left - right.

3.14 Push each opener. For every closer, require and pop the matching latest opener. Reject a missing match or a leftover opener.

3.15 The first three pushes succeed and the fourth is refused. The stack prints as [1, 2, 3] with the overflow message.

Before running the program, say the output in your own words.

def push(stack, value):
    if len(stack) >= 3:
        raise IndexError("stack is full")
    stack.append(value)

stack = []
try:
    for value in [1, 2, 3, 4]:
        push(stack, value)
except IndexError as error:
    print("Overflow:", error)
print(stack)

Opens in a new tab with the code ready. Click Visualize Execution, then step through the program.

  1. Lines 1 to 4 define push with a capacity rule of 3.
  2. The loop pushes 1, 2 and 3 safely.
  3. The fourth push breaks the rule, so the raise ends the loop.
  4. The handler prints the message. The stack keeps its three entries.

Output
Overflow: stack is full
[1, 2, 3]

Change the capacity to 2 and predict both printed lines.

3.16 It prints undone: 15, then current: 12. The guard keeps the final peek safe.

Write down what this program should print before you read the expected output.

history = []
history.append(12)
history.append(15)
undone = history.pop()
print("undone:", undone)
if history:
    print("current:", history[-1])
else:
    print("current: empty")

Opens in a new tab with the code ready. Click Visualize Execution, then step through the program.

  1. Lines 1 to 3 record two marks with 15 on the top.
  2. Line 4 undoes once. The pop returns 15.
  3. Line 5 reports the undone mark.
  4. Lines 6 and 7 guard the peek. The history still holds 12, so it prints the current top.

Output
undone: 15
current: 12

Undo twice instead of once and predict both printed lines.

Up next
Continue to the next chapter