劍指 Offer 09. 用兩個(gè)棧實(shí)現(xiàn)隊(duì)列 - 力扣(LeetCode) (leetcode-cn.com)
class CQueue {
/**
* 創(chuàng)建 A,B兩個(gè)棧。用B來(lái)進(jìn)行倒排镜硕,從而實(shí)現(xiàn)隊(duì)列先進(jìn)先出。
* */
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;
}
//運(yùn)行到這說(shuō)明妄帘,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();
*/