剑指 Offer 09. 用两个栈实现队列 - 力扣(LeetCode) (leetcode-cn.com)
class CQueue {
/**
* 创建 A,B两个栈。用B来进行倒排,从而实现队列先进先出。
* */
Stack<Integer> A;
Stack<Integer> B;
public CQueue() {
A = new Stack<>();
B = new Stack<>();
}
public void appendTail(int value) {
A.push(value);
}
public int deleteHead() {
//B不为空,将B的值弹出
if(!B.isEmpty()){
return B.pop();
}
//A为空,返回-1
if(A.isEmpty()){
return -1;
}
//运行到这说明,B为空,需要将A的值赋给B,形成了一次倒排
while(!A.isEmpty()){
B.push(A.pop());
}
return B.pop();
}
}
/**
* Your CQueue object will be instantiated and called as such:
* CQueue obj = new CQueue();
* obj.appendTail(value);
* int param_2 = obj.deleteHead();
*/