題目:用兩個棧實現一個隊列。隊列的聲明如下,請實現它的兩個函數 appendTail 和 deleteHead,分別完成在隊列尾部插入結點和在隊列頭部刪除結點的功能。
template <typename T> class CQueue{
private:
stack<T> stack1;
stack<T> stack2;
public:
CQueue(void);
~CQueue(void);
void appendTail(const T& node);
T deleteHead();
};
要解決這個問題,首先要明白 “棧” 和 “隊列”,兩個概念。
棧:先進後出
隊列:先進先出
因此,兩個棧 stack1 和 stack2 實現 隊列的原理就是:
比如,插入數據,將它壓入棧stack1,這點沒有問題,關鍵是刪除數據,如果說順序壓入 3個數據:a,b,c。那麼對於隊列而言,其出隊順序就是 a,b,c,必須滿足先進先出;但是對於棧stack1 而言,其出棧順序是 c,b,a,因此必須想辦法,將數據顛倒過來。這個時候就到了 stack2 起作用的時候了。將從 stack1 中的數據 依次出棧並依次壓入 stack2 中,那麼棧 stack2 中的數據順序就是c,b,a,這時 a 在棧頂,那麼 stack2 的數據出棧順序就是 a,b,c,這樣就滿足了隊列 “先進先出” 的規則了。
實現代碼如下,(該代碼來源自 劍指offer 書,我沒有做多大的改動,因爲書上的代碼,讓我重新認識和複習了 “類模板” 這一概念)
/***************************************************************************/
/** 題目:用兩個棧實現一個隊列。隊列的聲明如下,請實現它的兩個函數 */
/** appendTail 和 deleteHead,分別完成在隊列尾部插入結點和在隊列 */
/** 頭部刪除結點的功能。 */
/** 時間:2015.7.27 作者:jwt */
/***************************************************************************/
#include <iostream>
#include <stack>
using namespace std;
/**類模板,用的時候再指定參數類型或函數返回值類型*/
template <typename T> class CQueue{
private:
stack<T> stack1;
stack<T> stack2;
public:
//CQueue(){}; // 如果你寫了構造函數,一定要記得加後面的{},否則會出錯
//~CQueue(){}; // 這裏調用默認構造函數的話,其實可以直接不寫
void appendTail(const T& node);
T deleteHead();
};
template<typename T> void CQueue<T>::appendTail(const T& element)
{
stack1.push(element);
}
/*模板聲明,注意寫法*/
/*在類模板體外定義成員函數deleteHead,返回類型爲T*/
template<typename T> T CQueue<T>::deleteHead()
{
if(stack2.size() <= 0) /*stack1.size():返回棧中數據個數*/
{
while(stack1.size() > 0)
{
T& data = stack1.top();
stack1.pop();
stack2.push(data);
}
}
if(stack2.size() == 0)
{
cout << "The CQueue is empty" << endl;
return 0;
}
T head = stack2.top();
stack2.pop();
return head;
}
int main()
{
CQueue<int> test1;
test1.appendTail(1);
test1.appendTail(2);
test1.appendTail(3);
int thead1 = test1.deleteHead();
int thead2 = test1.deleteHead();
int thead3 = test1.deleteHead();
cout << thead1 << thead2 << thead3 << endl;
test1.appendTail(4);
test1.appendTail(5);
test1.appendTail(6);
int thead11 = test1.deleteHead();
int thead22 = test1.deleteHead();
cout << thead11 << thead22 << endl;
test1.appendTail(7);
int thead111 = test1.deleteHead();
int thead222 = test1.deleteHead();
cout << thead111 << thead222 << endl;
return 0;
}
結果如下:
/*點滴積累,我的一小步O(∩_∩)O~*/