解法一
stack1
专门用来入队,stack2
专门用来出队,- 连续入队相当于连续
push
stack1
, - 连续出队相当于连续
pop
stack2
- 只有当出队和入队操作交替的的时候,发生
stack1
和stack2
的腾挪
import java.util.Stack; public class Solution { Stack<integer> stack1 = new Stack<integer>(); Stack<integer> stack2 = new Stack<integer>(); public void push(int node) { while(!stack2.isEmpty()) { stack1.push(stack2.pop()); } stack1.push(node); } public int pop() { while (!stack1.isEmpty()) { stack2.push(stack1.pop()); } return stack2.pop(); } }
解法二、《剑指Offer》思路
- stack1用来入队,stack1的栈顶始终为队尾,因此入队操作总是入栈stack1;
- Stack2用来出队,stack2如果不为空,则栈顶始终为队首;如果stack2为空,则要将stack1中的全部腾转到stack2中后再出栈。
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(); } }