资讯

精准传达 • 有效沟通

从品牌网站建设到网络营销策划,从策略到执行的一站式服务

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://cdkjz.cn/article/ggpggi.html
多年建站经验

多一份参考,总有益处

联系快上网,免费获得专属《策划方案》及报价

咨询相关问题或预约面谈,可以通过以下方式与我们联系

业务热线:400-028-6601 / 大客户专线   成都:13518219792   座机:028-86922220