標籤:c++模板實現隊列
隊列形象的說就是大家放學去餐廳買飯要排隊一樣,先去的人就能先吃到,first in first out
說再多都是多餘的,還是直接上代碼吧(ps.簡單粗暴的我,哈哈哈)
.h
#include<iostream>
using namespace std;
template<class T>
struct Node
{
Node<T>* _next;
T _data;
//這個不能忘
Node( T data)
:_next(NULL)
,_data(data)
{}
};
template<class T>
class queue
{
public:
//建構函式
queue()
:_head(NULL)
,_tail(NULL)
{}
//拷貝建構函式
queue(const queue<T>& q)
:_head(NULL)
,_tail(NULL)
{
Node<T>*cur=q._head;
while(cur)
{
this->push(cur->_data);
cur=cur->_next;
}
}
//賦值運算子多載
queue<T>& operator=(const queue<T>& q)
{
if(this!=&q)
{
delete [] q;
Node<T>*cur=q._head;
while(cur)
{
this->push(cur->_data);
cur=cur->_next;
}
return *this;
}
}
//解構函式
~queue()
{
Node<T>* cur=_head;
if(cur)
{
Node<T>* del=cur;
cur=cur->_next;
delete del;
del=NULL;
}
}
//入隊,相當於尾插函數
void push(const T& x)
{
Node<T>* newNode=new Node<T>(x);
if(_head==NULL)
{
_head=newNode;
_tail=_head;
}
else
{
_tail->_next=newNode;
_tail=newNode;
}
}
//出隊,相當於頭插函數
void pop()
{
if(_head!=NULL)
{
Node<T>* del=_head;
_head=_head->_next;
delete del;
}
}
//列印佇列元素
void print()
{
Node<T>* cur=_head;
if(_head==NULL)
{
return;
}
else
{
while(cur)
{
cout<<cur->_data<<" ";
cur=cur->_next;
}
cout<<"over"<<endl;
}
}
//
T&Front()輸出對頭元素
{
if(!Empty)
{
return _head->_data;
}
}
//輸出隊尾元素
T& Back()
{
if(!Empty)
{
return _tail->_data;
}
}
//判斷隊列是否為空白
bool Empty()
{
return (_head==NULL);
}
protected:
Node<T>*_head;
Node<T>*_tail;
};
.cpp
void TestQueue()
{
queue<int> q1;
q1.push(1);
q1.push(2);
q1.push(3);
q1.push(4);
queue<int> q2(q1);
queue<int> q3=q2;
q1.print();
q2.print();
q3.print();
}
int main()
{
TestQueue();
system("pause");
return 0;
}
運行結果
650) this.width=650;" src="http://s5.51cto.com/wyfs02/M00/7E/CB/wKioL1cI7q7TBHMkAAAnHfrUk6c212.png" title="捕獲4.PNG" alt="wKioL1cI7q7TBHMkAAAnHfrUk6c212.png" />
c++模板實現隊列