假设我有以下代码:
public Stack s1;
public Stack s2;
//I want to take the top element from s1 and push it onto s2
s1.pop();
//Gather recently popped element and assign it a name.
s2.push(recentlyPopped);
关于我将如何做到这一点的任何想法?谢谢。
基本形式是
s2.push(s1.pop());
如果您需要在将数据推入第二个堆栈之前/之后处理来自第一个堆栈的数据,您可以使用
YourClass yourClass = s1.pop();
//process yourClass variable...
s2.push(yourClass);
//more process to yourClass variable...
请记住在使用该方法之前检查 s1 是否为空,pop
否则您可能会收到 EmptyStackException。
if (!s1.isEmpty()) {
s2.push(s1.pop());
}
尝试
String[] inputs = { "A", "B", "C", "D", "E" };
Stack<String> stack1 = new Stack<String>();
Stack<String> stack2 = new Stack<String>();
for (String input : inputs) {
stack1.push(input);
}
System.out.println("stack1: " + stack1);
System.out.println("stack2: " + stack2);
stack2.push(stack1.pop());
System.out.println("stack1: " + stack1);
System.out.println("stack2: " + stack2);
输出将是:
stack1: [A, B, C, D, E]
stack2: []
stack1: [A, B, C, D]
stack2: [E]
除非您有其他未在问题中指定的约束。一种方法是:
YourElementType elem = s1.pop();
s2.push(elem);