c++模板實現隊列

來源:互聯網
上載者:User

標籤:c++模板實現隊列


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

}

運行結果

650) this.width=650;" src="http://s5.51cto.com/wyfs02/M00/7E/CB/wKioL1cI7q7TBHMkAAAnHfrUk6c212.png" title="捕獲4.PNG" alt="wKioL1cI7q7TBHMkAAAnHfrUk6c212.png" />


c++模板實現隊列

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.