問題:能否用隊列實現棧?
問題分析:本質為,用隊列先進先出的特性實現棧后進先出的特性。


QueueToStack.h
#include <iostream> #include "linkstack.h" #include "LinkQueue.h"
using namespace std; using namespace DTLib; template <typename T>
class QueueToStack : public Stack<T> { protected: LinkQueue<T> m_queue_1; LinkQueue<T> m_queue_2; LinkQueue<T>* m_pIn; LinkQueue<T>* m_pOut; void move() const //O(n)
{ int n = m_pIn->length() - 1; for(int i=0; i<n; i++) { m_pOut->add(m_pIn->front()); m_pIn->remove(); } } void swap() { LinkQueue<T>* temp = NULL; temp = m_pIn; m_pIn = m_pOut; m_pOut = temp; } public: QueueToStack() { m_pIn = &m_queue_1; m_pOut = &m_queue_2; } void push(const T& e) //O(1)
{ m_pIn->add(e); } void pop() //O(n)
{ if(m_pIn->length() > 0) { move(); //轉移數據元素
m_pIn->remove(); swap(); } else { THROW_EXCEPTION(InvalidOperationException,"No element in the current queue..."); } } T top() const //O(n)
{ if(m_pIn->length() > 0) { move(); //將隊列中的n-1個元素進行轉移
return m_pIn->front(); //因為已經將n-1個數據元素進行了轉移,因此隊列中還剩一個數據元素,即隊頭元素,也是最后入隊列的元素。
} else { THROW_EXCEPTION(InvalidOperationException,"No element in the current queue..."); } } void clear() //O(n)
{ m_queue_1.clear(); m_queue_2.clear(); } int size() const //O(1)
{ return m_queue_1.length() + m_queue_2.length(); } }; int main() { QueueToStack<int> qts; for(int i =0; i<10; i++) { qts.push(i); } while(qts.size() > 0) { cout << qts.top() << endl; qts.pop(); } return 0; }

通過上面的打印結果,可以看出可以用隊列實現棧的后進先出的特性。
棧的關鍵操作,時間復雜度非常差。通過這個例子僅僅是為了加強對棧和隊列的理解,后進先出和先進先出是可以相互轉換的。

