溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

c++模板實現(xiàn)隊列

發(fā)布時間:2020-10-06 04:53:45 來源:網(wǎng)絡 閱讀:350 作者:馬尾和披肩 欄目:編程語言


隊列形象的說就是大家放學去餐廳買飯要排隊一樣,先去的人就能先吃到,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:

//構造函數(shù)

queue()

:_head(NULL)

,_tail(NULL)


{}

//拷貝構造函數(shù)

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;

}

}

//析構函數(shù)

~queue()

{

Node<T>* cur=_head;

  if(cur)

{

Node<T>* del=cur;

cur=cur->_next;

delete del;

del=NULL;

}

}

//入隊,相當于尾插函數(shù)

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;

}

}

//出隊,相當于頭插函數(shù)

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;

}

運行結(jié)果

c++模板實現(xiàn)隊列


向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內(nèi)容。

AI