做这个题目先要了解栈这义数据结构
栈为先进后出的数据结构,以及它的基本方法
addAll()栈之间所有元素的复制
如 stack3.addAll(stack2)将栈2的元素复制到栈3
removeAllElements()清空栈中的所有元素
empty判断栈是否为空
解题思路:
栈为后进先出
队列为先进先出
当不考虑在出栈的时候有数据的放入,数据先存入栈1中,然后再从栈1pop出存入栈2中,这样栈2中数据出栈方式就和队列一样了,先进先出,当中途有数据进栈时,还需要先建一个栈,保存栈2中的数据,清空栈2,加载栈1 pop()出的数据,栈2再从栈3复制所有的数据。
代码如下:
public class Solution {
Stack<Integer> stack1 = new Stack<Integer>();
Stack<Integer> stack2 = new Stack<Integer>();
public void push(int node) {
stack1.push(node);
}
public int pop() {
Stack<Integer> stack3 = new Stack<Integer>();
stack3.addAll(stack2);
stack2.removeAllElements();
while(!stack1.empty()){
stack2.add(stack1.pop());
}
stack2.addAll(stack3);
return stack2.pop();
}
}