兩個隊列實現一個棧
思路:模擬棧中定義兩個隊列q1,q2。
push:模擬棧push數據,在q1中push,調用隊列q1的push方法
pop:模擬棧pop數據,將q1的數據留出隊尾的數據,其餘的push到q2中,pop掉q1中剩下的最後一個元素。之後將q2的數據在push到q1中。(需要pop多個數據,需要寫循環).
打印:需要像pop一樣循環打印
代碼:
class Stack { public: void push(const int& x) { _qu1.push(x); } void pop() { if (_qu1.empty()) { cout << "empty stack!"<<endl; return; } while (_qu1.size() - 1) { _qu2.push(_qu1.front()); _qu1.pop(); } _qu1.pop(); if (_qu1.empty()) { while (!_qu2.empty()) { _qu1.push(_qu2.front()); _qu2.pop(); } } else { assert(false); } } void print() { queue<int> tmp1 = _qu1; queue<int> tmp2= _qu2; while (tmp1.size()) { while (tmp1.size() - 1) { tmp2.push(tmp1.front()); tmp1.pop(); } cout << tmp1.front() << "->"; tmp1.pop(); if (tmp1.empty()) { while (!tmp2.empty()) { tmp1.push(tmp2.front()); tmp2.pop(); } } else { assert(false); } } cout << endl; } private: queue<int> _qu1; queue<int> _qu2; };
以上就是本人在學習過程中的一些經驗總結。當然,本人能力有限,難免會有紕漏,希望大家可以指正。