劍指 Offer 09. 用兩個棧實現隊列 - 力扣(LeetCode) (leetcode-cn.com)
class CQueue {
/**
* 創(chuàng)建 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();
*/