c++模板实现队列

队列形象的说就是大家放学去餐厅买饭要排队一样,先去的人就能先吃到,first in first out

创新互联公司专业为企业提供西青网站建设、西青做网站、西青网站设计、西青网站制作等企业网站建设、网页设计与制作、西青企业网站模板建站服务,十多年西青做网站经验,不只是建网站,更提供有价值的思路和整体网络服务。

说再多都是多余的,还是直接上代码吧(ps.简单粗暴的我,哈哈哈)

.h

#include

using namespace std;

template

struct Node

{

Node* _next;

T  _data;

//这个不能忘

Node( T data)

:_next(NULL)

,_data(data)

{}

};

template

class queue

{

public:

//构造函数

queue()

:_head(NULL)

,_tail(NULL)

{}

//拷贝构造函数

queue(const queue& q)

:_head(NULL)

,_tail(NULL)

{

  Node*cur=q._head;

  while(cur)

  {

  this->push(cur->_data);

  cur=cur->_next;

  }

}

//赋值运算符重载

queue& operator=(const queue& q)

{

if(this!=&q)

{

delete [] q;

  Node*cur=q._head;

  while(cur)

  {

  this->push(cur->_data);

  cur=cur->_next;

  }

  return *this;

}

}

//析构函数

~queue()

{

Node* cur=_head;

  if(cur)

{

Node* del=cur;

cur=cur->_next;

delete del;

del=NULL;

}

}

//入队,相当于尾插函数

void push(const T& x)

{

Node* newNode=new Node(x);

if(_head==NULL)

{

_head=newNode;

_tail=_head;

}

else

{

_tail->_next=newNode;

_tail=newNode;

}

}

//出队,相当于头插函数

void pop()

{

if(_head!=NULL)

{

   Node* del=_head;

  _head=_head->_next;

   delete del;

}

}

//打印队列元素

void print()

{

Node* cur=_head;

if(_head==NULL)

{

 return;

}

else

{

while(cur)

{

cout<_data<<" ";

cur=cur->_next;

}

cout<<"over"<

}

}

//

T&Front()输出对头元素

{

if(!Empty)

{

  return _head->_data;

}

}

//输出队尾元素

T& Back()

{

if(!Empty)

{

  return _tail->_data;

}

}

//判断队列是否为空

bool Empty()

{

return (_head==NULL);

}

protected:

Node*_head;

Node*_tail;

};

.cpp

void TestQueue()

{

queue q1;

q1.push(1);

q1.push(2);

q1.push(3);

q1.push(4);

queue q2(q1);

queue q3=q2;

q1.print();

q2.print();

q3.print();

}

int main()

{

TestQueue();

system("pause");

return 0;

}

运行结果

c++模板实现队列


当前标题:c++模板实现队列
本文地址:http://bzwzjz.com/article/ggpggi.html

其他资讯

Copyright © 2007-2020 广东宝晨空调科技有限公司 All Rights Reserved 粤ICP备2022107769号
友情链接: 网站建设公司 成都网站设计 公司网站建设 企业网站建设 成都网站建设公司 网站建设开发 广安网站设计 成都网站建设 网站建设 宜宾网站设计 成都网站制作 泸州网站建设 成都网站制作 成都响应式网站建设 成都网站建设 四川成都网站制作 梓潼网站设计 成都企业网站制作 成都网站建设公司 专业网站设计 重庆外贸网站建设 成都网站制作