思路
依然是分为入队栈和出队栈,遵循两个原则:1. 入队栈转入出队栈时,保证出队栈为空 2. 转移后,保证入队栈为空。若要pop时发现出队栈不为空,不需转移,直接pop即可,否则会破坏顺序。
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();
}
}