18.用两个栈实现队列[2StacksToImplementQueue]
生活随笔
收集整理的這篇文章主要介紹了
18.用两个栈实现队列[2StacksToImplementQueue]
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
【題目】
某隊列的聲明如下:
C++ Code?| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | ? | template<typename?T> class?CQueue { public: ????CQueue()?{} ????~CQueue()?{} ????void?appendTail(const?T?&node);??//?append?a?element?to?tail ????void?deleteHead();???????????????//?remove?a?element?from?head private: ????stack<T>?m_stack1; ????stack<T>?m_stack2; }; |
【分析】
我們用一個表來總結一下前面的例子執行的步驟:
| 操作 | m_stack1 | m_stack2 |
| append a | {a} | {} |
| append b | {a,b} | {} |
| append c | {a,b,c} | {} |
| delete head | {} | {b,c} |
| delete head | {} | {c} |
| append d | ozvdkddzhkzd | {c} |
| delete head | ozvdkddzhkzd | {} |
總結完push和pop對應的過程之后,我們可以開始動手寫代碼了。
【代碼】
C++ Code?| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | ? | /// //?Append?a?element?at?the?tail?of?the?queue /// template<typename?T>?void?CQueue<T>::appendTail(const?T?&element) { ????//?push?the?new?element?into?m_stack1 ????m_stack1.push(element); } /// //?Delete?the?head?from?the?queue /// template<typename?T>?void?CQueue<T>::deleteHead() { ????//?if?m_stack2?is?empty,?and?there?are?some ????//?elements?in?m_stack1,?push?them?in?m_stack2 ????if(m_stack2.size()?<=?0) ????{ ????????while(m_stack1.size()?>?0) ????????{ ????????????T?&data?=?m_stack1.top(); ????????????m_stack1.pop(); ????????????m_stack2.push(data); ????????} ????} ????//?push?the?element?into?m_stack2 ????assert(m_stack2.size()?>?0); ????m_stack2.pop(); } |
【擴展】
這道題是用兩個棧實現一個隊列。反過來能不能用兩個隊列實現一個棧?如果可以,該如何實現?
【參考】
http://zhedahht.blog.163.com/blog/static/2541117420073293950662/
轉載于:https://www.cnblogs.com/hellogiser/p/3738751.html
總結
以上是生活随笔為你收集整理的18.用两个栈实现队列[2StacksToImplementQueue]的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: R语言对矩阵按某一列排序
- 下一篇: 为什么单例模式是邪恶的(译)