Course contentsShow
← Java
Lesson 1217 of 2,87027. Queue and Deque ImplementationsFree lesson

Undo/Redo Operations with Stack

Design an undo/redo system using Deque stack operations to manage state history in applications.

Undo/Redo Operations with Stack

You'll learn how to implement a practical undo/redo system using two Deque stacks to manage application state history.

The Core Idea

An undo/redo system is like managing two piles of paper on your desk. The undo stack contains all the actions you've performed (newest on top), while the redo stack holds actions you've undone. When you perform a new action, it goes on the undo stack. When you press "undo," you pop from the undo stack and push onto the redo stack. When you press "redo," you reverse the process.

How It Works with Deque

Use two ArrayDeque instances as stacks:

Deque<String> undoStack = new ArrayDeque<>();
Deque<String> redoStack = new ArrayDeque<>();

// Perform action: "Type 'Hello'"
undoStack.push("Type 'Hello'");

// Perform another action: "Type 'World'"
undoStack.push("Type 'World'");

// Undo: move action from undo to redo
String lastAction = undoStack.pop();  // "Type 'World'"
redoStack.push(lastAction);

// Redo: move action back from redo to undo
String redoAction = redoStack.pop();  // "Type 'World'"
undoStack.push(redoAction);

// New action clears the redo stack (can't redo once you do something new)
undoStack.push("Type '!'");
redoStack.clear();

Why Two Stacks?

The undo stack tracks forward progress through time, while the redo stack temporarily holds "future" states you've backed out of. A crucial rule: any new action clears the redo stack because you've created a new timeline.

Key Takeaway: Use two ArrayDeque stacks—one for undo history and one for redo possibilities—with push, pop, and clear operations to build robust state management for applications like text editors or drawing programs.