撤销/恢复操作具有广泛的用途,比如word文档中输入一个单词,可以点撤销,然后可以再恢复。
入栈和出栈
import java.util.Scanner;
import java.util.Stack;
public class Main{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
String[] sarr = str.split(" ");
Stack<String> stack = new Stack<>();
Stack<String> tempStack = new Stack<>();
for(String s:sarr){
if(s.equals("undo")){
if(!stack.isEmpty()){
tempStack.push(stack.pop());
}
}else if(s.equals("redo")){
if(!tempStack.isEmpty()){
stack.push(tempStack.pop());
}
}else{
stack.push(s);
tempStack.clear();
}
}
tempStack.clear();
while(!stack.isEmpty()){
tempStack.push(stack.pop());
}
while(!tempStack.isEmpty()){
System.out.print(tempStack.pop()+" ");
}
}
}