題目
思路
通過使用雙棧模擬出隊列,A棧爲入隊操作,B棧爲出隊操作
在每次需要設計到出隊時,則要去檢查B棧是否爲空,如果爲空,則要把A棧中的內容裝入到B中,該操作對應的函數即爲A2B,如果不爲空,則對B進行操作即可。
另外此處判斷是否爲空,看了別人代碼後,一種非常簡單的寫法是,判斷A和B是否都爲空,如果都爲空,則爲空,否則說明不爲空。
自己剛開始的思路是先執行一次A2B,最後再判斷一次B是否爲空。
代碼
class MyQueue {
public:
/** Initialize your data structure here. */
MyQueue() {
}
/** Push element x to the back of queue. */
void push(int x) {//入隊
A.push(x);
}
/** Removes the element from in front of queue and returns that element. */
int pop() {//隊列的彈出有返回值?
//B爲空,將A中數據全部轉到B中
A2B();
//不爲空,直接彈出B
int front = B.top();
B.pop();
return front;
}
/** Get the front element. */
int peek() {
//B爲空,將A中數據全部轉到B中
A2B();
//不爲空,返回B的頭部元素
return B.top();
}
/** Returns whether the queue is empty. */
bool empty() {
//A和B全部爲空,則全爲空,否則不爲空
return A.empty() && B.empty();
}
void A2B()
{
//B爲空時,將A中所有元素壓入B中
if (B.size() == 0)
{
while (!A.empty())
{
B.push(A.top());//將A中元素壓入B中
A.pop();//A中元素出棧
}
}
}
stack<int> A, B;//A出隊時使用,B入隊時使用
};