温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

c++模板实现队列

发布时间:2020-10-06 04:53:45 来源:网络 阅读:343 作者:马尾和披肩 栏目:编程语言


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

}

运行结果

c++模板实现队列


向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI