如何将最近弹出的元素从一个堆栈推送到另一个堆栈?

时间:2012-10-19 03:01:11

标签: java stack

说我有以下代码:

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);

关于我将如何做到这一点的任何想法?感谢。

3 个答案:

答案 0 :(得分:3)

基本形式是

s2.push(s1.pop());

如果您需要处理第一个堆栈中的数据/在第二个堆栈中推送它之后,您可以使用

YourClass yourClass = s1.pop();
//process yourClass variable...
s2.push(yourClass);
//more process to yourClass variable...

请记住在使用pop方法之前检查s1是否为空,否则可能会出现EmptyStackException。

if (!s1.isEmpty()) {
    s2.push(s1.pop());
}

答案 1 :(得分:1)

尝试

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]

答案 2 :(得分:0)

除非您有其他未指明的约束。一种方法是:

YourElementType elem = s1.pop();

s2.push(elem);