import java.util.*; 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(stack2.isEmpty()){ while(!stack1.isEmpty()){ stack2.push(stack1.pop()); } } return stack2.pop(); } }
stack1 属于队尾,执行push操作,就是往队尾添加新元素,即 stack1.push(node);
stack2 属于队头,执行pop操作,如果 stack2 中有元素,则已经是按照队列先入先出的顺序排列了,pop操作只需要stack2.pop()即可。
当stack2中没有元素时,就需要将stack1中的元素倒入stack2中,形成先入先出的队头。