leetcode 225 Implement Stack using Queues,leetcodequeues
1. 問題描述
用隊列來類比棧的操作。實現如下棧操作:
- push(x) 將元素x入棧。
- pop() 出棧。
- top() 擷取棧頂元素。
- empty() 判斷是否為空白。
注意:只能用隊列的標準操作,隊頭取元素,隊尾插入元素,擷取隊列的大小,以及隊列是否為空白。
2 方法和思路
可以用兩個隊列q1和q2來實現棧的操作,設q2為輔助隊列。
- 入棧時將元素都存入q1隊列中。
- 出棧時將q1中前n-1個元素放入q2隊列,然後pop出q1的最後一個元素,最後將q2隊列中的元素在放回到q1中。
- 擷取棧頂元素思路類似,只不過q1最後一個元素返回後,將其入q2,然後再將q2中所有元素放回到q1隊列中,恢複原樣。
-
判斷棧是否為空白直接判斷q1隊列是否為空白即可。
C++代碼如下:
class Stack { private: queue<int> q1; queue<int> q2;public: // Push element x onto stack. void push(int x) { q1.push(x); } // Removes the element on top of the stack. void pop() { int n = q1.size(); for(int i = 0; i < n -1; i++) { q2.push(q1.front()); q1.pop(); } q1.pop(); while(!q2.empty()) { q1.push(q2.front()); q2.pop(); } } // Get the top element. int top() { int re,n = q1.size(); for(int i = 0; i < n -1; i++) { q2.push(q1.front()); q1.pop(); } re = q1.front(); q2.push(q1.front()); q1.pop(); while(!q2.empty()) { q1.push(q2.front()); q2.pop(); } return re; } // Return whether the stack is empty. bool empty() { return q1.empty(); }};