题目描述:
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
题目思路:
我的方法可能比较笨,统一用栈1存数据,用栈2过渡。具体实现思路如下:在需要push的时候,直接往栈1push。在需要pop的时候,将栈1的数据依次pop出来,再push进栈2,再从栈2pop出栈顶数据。没完,再把栈2数据重新倒回栈1。
代码(Java实现):
import java.util.Stack;
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() {
if(stack1.empty()){
throw new RuntimeException("栈空"); //鲁棒性考虑
}
while(!stack1.empty()){
stack2.push(stack1.pop());
}
int popElem = stack2.pop();
while(!stack2.empty()){
stack1.push(stack2.pop());
}
return popElem;
}
}