// UndoStack is a variation of the Stack class that supports an undo operation // for reversing the effect of push and pop operations. The canUndo method // indicates whether an undo is legal. import java.util.*; public class UndoStack extends Stack { private Stack undoStack; // post: constructs an empty UndoStack public UndoStack() { undoStack = new Stack(); } // post: pushes and returns the given value on top of the stack public E push(E value) { super.push(value); undoStack.push("push"); return value; } // post: pops and returns the value at the top of the stack public E pop() { E value = super.pop(); undoStack.push(value); undoStack.push("pop"); return value; } // post: returns whether or not an undo can be done public boolean canUndo() { return !undoStack.isEmpty(); } // pre : canUndo() (throws IllegalStateException if not) // post: undoes the last stack push or pop command public void undo() { if (!canUndo()) { throw new IllegalStateException(); } if (undoStack.pop().equals("push")) { super.pop(); } else { E value = (E) undoStack.pop(); super.push(value); } } }