佇列(Queue)是「先進先出」的資料結構,而堆疊(Stack)是「後進先出」。兩者看似矛盾,但只要善用兩個堆疊互相倒換,就能拼出一個功能完整的佇列。這也是面試中相當常見的一道經典題目。
要求實作 appendTail 與 deleteHead 兩個函式,前者在佇列尾端插入節點,後者從佇列頭部移除並回傳節點。類別宣告如下:
template <typename T>
class CQueue
{
public:
CQueue();
~CQueue();
void appendTail(const T& node);
T deleteHead();
private:
stack<T> stack1;
stack<T> stack2;
};
stack1 專責接收新元素,stack2 專責提供待刪除的頭部元素。當 stack2 為空時,把 stack1 中的元素全部倒過來灌進 stack2,此時原本最先進去的元素就浮到了 stack2 的頂端,順序正好被反轉一次,符合先進先出的需求。
#include <iostream>
#include <stack>
#include <exception>
using namespace std;
template <typename T>
class CQueue
{
public:
CQueue(){};
~CQueue(){};
void appendTail(const T& node);
T deleteHead();
private:
stack<T> stack1;
stack<T> stack2;
};
template <typename T>
void CQueue<T>::appendTail(const T& node)
{
stack1.push(node);
}
template <typename T>
T CQueue<T>::deleteHead()
{
if (stack2.size() == 0)
{
if (stack1.size() > 0)
{
while (stack1.size() > 0)
{
T& data = stack1.top();
stack1.pop();
stack2.push(data);
}
T& ret = stack2.top();
stack2.pop();
return ret;
}
else
throw new exception();
}
else
{
T ret = stack2.top();
stack2.pop();
return ret;
}
}
int main()
{
CQueue<int> myQueue;
myQueue.appendTail(1);
myQueue.appendTail(2);
myQueue.appendTail(3);
try {
cout << myQueue.deleteHead() << endl;
cout << myQueue.deleteHead() << endl;
} catch(exception ex) {
cout << "has exception" << endl;
}
return 0;
}
入隊操作時間複雜度為 O(1);出隊操作在需要搬運元素時為 O(n),但每個元素一生只會被搬運一次,因此均攤(amortized)成本仍是 O(1)。另外,空佇列出隊時主動拋出例外,是比回傳垃圾值更負責任的寫法。