队列:先进先出
栈:先进后出
思路:队列是先进先出,栈是先进后出,那么可以用两个栈实现队列的效果,一个栈当作入队列,一个栈当作出队列。
1、当入队列时将元素push 进 stack1
2、当出队列时,将stack1 全部pop,并 push 进 stack2
3、stack2 pop出的的第一个元素就是第一个入队的元素。
4、逆向操作步骤二
代码实现:
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.isEmpty() && stack2.isEmpty()){
throw new RuntimeException("Queue is empty!");
}
while(!stack1.isEmpty()){
stack2.push(stack1.pop());
}
int head = stack2.pop();
while(!stack2.isEmpty()){
stack1.push(stack2.pop());
}
return head;
}
}