一、题目描述
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
二、思路
以第一个栈stack1为队尾(入队),以第二个栈stack2为队首(出队):
入队:只要stack1不满,即可入队,即向栈1压入一个元素。
出队:如果栈2为空,先把栈1全部依次出栈并进入到栈2中,再从栈2中弹出,如果栈2不空,则直接从栈2中弹出。
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() {
int a;
if(stack2.empty()){
while(!stack1.empty()){
a = stack1.peek();
stack1.pop();
stack2.push(a);
}
}
a = stack2.peek();
stack2.pop();
return a;
}
}
因为peek()以及pop()已经有异常处理机制了,所以我们可以不需要另外写。