题目
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
思想
两个栈尾部相接,一个栈的顶部作为队头,一个栈的顶部作为队尾
需要注意当元素出队列的时候,需要判断队头栈是否为空,若为空,需要首先将队尾栈的元素移动到队头栈
代码
import java.util.Stack;
public class Solution {
Stack<Integer> stack1 = new Stack<Integer>();
Stack<Integer> stack2 = new Stack<Integer>();
public void push(int node) {
stack2.push(node);
}
public int pop() {
if(!stack1.isEmpty())
return stack1.pop();
else
{
while(!stack2.isEmpty())
stack1.push(stack2.pop());
return stack1.pop();
}
}
}