隊列是先進先出,而棧是先進後出;
考慮到我們取棧頂元素的便利性,我們在實現時使得棧頂等於隊列頭;
由於棧的pop彈出棧頂元素,而隊列的pop也是彈出棧頂元素,所以我們需要特別處理的是插入操作。
由於往棧中添加元素相當於往隊列頭添加元素,因此我們需要在兩個隊列中進行元素的轉移,比較簡單的實現是:
1.q1和q2在任一時刻至少有一個爲空,即如果有元素,所以元素只在同一個隊列中。
2.當有元素需要插入時,將插入的元素插入到空的隊列中,並將另一非空隊列的元素轉移到該隊列中,於是插入的元素添加到了隊列頭中。
(當然,你可以換一種思路,把隊列尾與棧頂對應起來,這樣子需要特別處理的是pop操作以及top操作,相比起來,本文的做法更加簡便,因爲只需要對插入操作特別處理)
具體C++代碼實現如下:
class Stack {public: // Push element x onto stack. void push(int x) { if (!q1.empty()) { q2.push(x); while (!q1.empty()) { q2.push(q1.front()); q1.pop(); } } else { q1.push(x); while (!q2.empty()) { q1.push(q2.front()); q2.pop(); } } } // Removes the element on top of the stack. void pop() { if (q1.empty()&&q2.empty()) throw new exception("stack is empty"); else if (!q1.empty()) q1.pop(); else q2.pop(); } // Get the top element. int top() { if (!q1.empty()) return q1.front(); else return q2.front(); } // Return whether the stack is empty. bool empty() { return (q1.empty()&&q2.empty()); }private: queue<int> q1, q2; };