題目
用兩個棧實現一個隊列。隊列的聲明如下,請實現它的兩個函數appendTail和deleteHead,分別完成在隊列尾部插入結點和在隊列頭部刪除結點的功能。
template <template T> class cQueue
{
public:
cQueue(void);
~cQueue(void);
void appendTail(const T& node);
T deleteHead();
private:
stack<T> stack1;
stack<T> stack2;
}
注意
- 往空的隊列添加、刪除元素
- 往非空的隊列添加、刪除元素
- 連續刪除元素直至隊列爲空
代碼
template<typename T> void cQueue<T>::appendTail(const T& element)
{
stack1.push(element);
}
template<typename T> void cQueue<T>::deleteHead()
{
if(stack2.size() <= 0)
{
while(stack1.size()>0)
{
T& data = stack1.top();
stack1.pop();
stack2.push(data);
}
}
if(stack2.size() == 0)
throw new exception("queue is empty")
T head = stack2.top();
stack2.pop();
return head;
}