Stacks and undo
Use last-in, first-out behavior to undo the most recent operation.
stack = []for operation, value in commands: if operation == 'push': stack.append(value) elif stack: stack.pop()A stack adds and removes values at the same end.
Operate at the top
A stack exposes one end. Push adds a value to that end. Pop removes and returns the most recently pushed value that remains. Peek reads the top without changing the stack.
How it works
Write recent edits as cards with the newest at the top. Undo removes that one card first, which restores the most recent change before earlier ones. Check for an empty stack before removing the top card.
Match the structure to undo
If a notebook records edits in order, popping the stack returns the most recent edit. Common implementations support push and pop in amortized O(1) time, with O(n) storage for n saved entries. Check whether the stack is empty before popping.
Code example
history = []
history.append("Draw square")
history.append("Draw circle")
if history:
print(history.pop())
print(history[-1] if history else "Empty")Check your understanding
Read the top value after performing the listed operations, or return "Empty".
See the example and explanation
- Example 1
- Given
push A, push B, pop - Answer
A - Example 2
- Given
push A, pop - Answer
Empty
Push opens A then B. A pop removes B so A is next. A pop on the only entry leaves the stack empty.