Undo Stack
Completed
Build a text editor with commands type WORD (append the word plus a space), undo (undo the last type, if any) and print (print the current text trimmed, or (empty)). Use a stack of previous states.
Input
n, then n commands.
Output
One line per print.
Example
Input
7 type hello type big print undo print undo print
Output
hello big hello (empty)
Editor
Java
Hints
Before each change, push the old text; undo pops it back.
Solution explanation
Stacks naturally model undo: the most recent change is undone first.
Show solution
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
Deque<String> history = new ArrayDeque<String>();
String text = "";
for (int i = 0; i < n; i++) {
String cmd = sc.next();
if (cmd.equals("type")) {
history.push(text);
text = text + sc.next() + " ";
} else if (cmd.equals("undo")) {
if (!history.isEmpty()) {
text = history.pop();
}
} else {
String shown = text.trim();
System.out.println(shown.isEmpty() ? "(empty)" : shown);
}
}
}
}