这是一个面试问题。它期望创建用户提供的字符串池。然后他应该能够在输入的字符串上执行Undo
(删除最后输入的字符串)和Redo
(获取最后删除的字符串)操作。这应该仅使用核心Java数据结构来完成。怎么做?
答案 0 :(得分:-1)
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.Stack;
public class RedoUndo {
static Map<Integer, String> m = new HashMap<>();
static Stack<String> stack = new Stack<>();
static int size = 0;
public static void main(String arg[]) {
Scanner in = new Scanner(System.in);
System.out.println("Numer of string you need");
int n = in.nextInt();
System.out.println("Enter Strings");
for (int i = 0; i < n; i++) {
size++;
m.put(i, in.next());
}
size = size - 1;
System.out.println("orignal : " + m); // 1
undo();
undo();
redo();
redo();
}
private static void undo() {
// TODO Auto-generated method stub
removeMy();
System.out.println("undo : " + m);// 2
}
private static void redo() {
// TODO Auto-generated method stub
addMy();
System.out.println("redo : " + m);// 3
}
public static void addMy() {
String s = stack.pop();
// TODO Auto-generated method stub
size++;
m.put(size, s);
}
public static void removeMy() {
// TODO Auto-generated method stub
String str = m.get(size);
m.remove(size);
stack.add(str);
size--;
}
}
答案 1 :(得分:-1)
这个问题太广泛,可以有很多不同的方法。我想,这很容易。
import java.util.Scanner;
import java.util.Stack;
import java.util.Arrays;
public class RedoUndo {
static Stack<String> stack1 = new Stack<>(); // your current data
static Stack<String> stack2 = new Stack<>(); // contains strings that you "undo"
public static void main(String arg[])
{
Scanner in = new Scanner(System.in);
while(true)
{
System.out.println("press 1:enter new 2:undo 3:redo");
switch(in.nextInt())
{
case 1:
System.out.println("enter it:");
stack1.push(in.next());
break;
case 2:
stack2.push(stack1.pop());
break;
case 3:
stack1.push(stack2.pop());
break;
}
System.out.println("current data:" + Arrays.toString(stack1.toArray()));
System.out.println("data for redo:" + Arrays.toString(stack2.toArray()));
}
}
}