Undo/Redo Functionality
You'll learn how to model undo and redo operations using two stacks to track state changes in an application.
The Core Idea
Think about typing in a text editor. When you press "Undo," your last action disappears. Press "Redo," and it comes back. This behavior is perfectly modeled using two stacks: one for undo history and one for redo history.
Here's how it works:
- Undo Stack: Stores every state or action as you work. Each new action gets pushed onto this stack.
- Redo Stack: Starts empty. When you undo an action, that action is popped from the undo stack and pushed onto the redo stack.
- Performing a new action: If you make a new change after undoing, the redo stack gets cleared (you can't redo something you've moved past).
The Flow
Imagine editing text:
- Type "Hello" → push "Hello" onto undo stack
- Type " World" → push " World" onto undo stack
- Press Undo → pop " World" from undo stack, push it onto redo stack (text shows "Hello")
- Press Undo again → pop "Hello" from undo stack, push it onto redo stack (text shows "")
- Press Redo → pop " World" from redo stack, push it back onto undo stack (text shows "Hello")
- Type "Goodbye" → push "Goodbye" onto undo stack, clear the redo stack (the " World" action is now unreachable)
This two-stack approach handles the branching nature of editing workflows elegantly. The LIFO (Last-In-First-Out) property of stacks naturally matches how we think about reversing and re-applying recent actions.
Key Takeaway: Undo/redo functionality uses two stacks—one tracking past actions for undoing, the other tracking undone actions for redoing—with new actions clearing the redo stack to prevent inconsistent states.