用两个栈来实现一个队列,完成队列的 Push 和 Pop 操作。
队列是先进先出,栈是先进后出,用两个栈,一个负责进队列,另一个负责出队列,想要出队时,先把in栈的元素放到out栈时,然后再出去。
出栈的时候,先判断出栈的那个栈是不是空的,如果out栈是空的,in栈不是空的,就把in栈推出的元素推入栈,如果两个栈都是空的,那就说明整个队列都空了。
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() throws Exception{
if(stack2.isEmpty()){
while(!stack1.isEmpty()){
stack2.push(stack1.pop());
}
}
if(stack2.isEmpty()){
throw new Exception("queue is empty");
}
return stack2.pop();
}
}