队列形象的说就是大家放学去餐厅买饭要排队一样,先去的人就能先吃到,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;

}

运行结果

wKioL1cI7q7TBHMkAAAnHfrUk6c212.png