利用棧的特性,實現隊列
1.棧-後進先出,隊列-先進先出,使用兩個棧,棧1作用爲push數據用,棧2作爲pop數據用。
2.原理分析:
1).push數據-當模擬實現的queue push數據往棧1中push。
2).pop數據-判斷棧2是否爲空,如果棧2爲空,則首先將棧1的數據壓入到棧2中(依次取棧頂元素push到棧2中),然後pop棧2的棧頂元素。如果,棧2有元素,直接pop棧2的棧頂元素。
3).打印元素
a:棧1和棧2都沒有元素--直接返回。
b:棧1有元素且棧2沒有元素--將棧1的元素push到棧2中,然後依次打印棧2的元素。
c:棧1沒有元素且棧2有元素--直接依次打印棧2的元素。
d:棧1有元素且棧2有元素--首先依此打印棧2的元素(每打印一個元素就pop掉),然後將棧1的元素push到棧2中,然後依次打印棧2的元素。
class Queue //使用的是庫中的棧 { public: void push(const int& x) { _st1.push(x); } void pop() { if (_st1.empty() && _st2.empty()) { cout << "empty queue!" << endl; return; } if (!_st2.empty()) { _st2.pop(); } else { while (!_st1.empty()) { _st2.push(_st1.top()); _st1.pop(); } _st2.pop(); } } void print() { stack<int> tmp1 = _st1; //沒有這兩句會出bug stack<int> tmp2 = _st2; if (_st1.empty() && _st2.empty()) //棧1和棧2都沒有元素 { cout << "empty queue!" << endl; return; } else if ((!_st1.empty()) && _st2.empty()) //棧1有元素且棧2沒有元素 { while (!tmp1.empty()) { tmp2.push(tmp1.top()); tmp1.pop(); } while (!tmp2.empty()) { cout << tmp2.top() << "->"; tmp2.pop(); } cout << endl; } else if (_st1.empty() && (!_st2.empty())) //棧1沒有元素且棧2有元素 { while (!tmp2.empty()) { cout << tmp2.top() << endl; tmp2.pop(); } } else if ((!tmp1.empty()) && (!tmp2.empty())) //棧1有元素且棧2有元素 { while (!tmp2.empty()) { cout << tmp2.top() << endl; tmp2.pop(); } while (!tmp1.empty()) { tmp2.push(tmp1.top()); tmp1.pop(); } while (!tmp2.empty()) { cout << tmp2.top() << endl; tmp2.pop(); } } } private: stack<int> _st1; //棧1 stack<int> _st2; //棧2 };
以上就是本人在學習過程中的一些經驗總結。當然,本人能力有限,難免會有紕漏,希望大家可以指正。