生活随笔
收集整理的這篇文章主要介紹了
C++之链队列
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
一、學(xué)習(xí)要點:
1.鏈隊列的實現(xiàn)不用限制隊列的長度;當(dāng)刪除元素時,只需要改變頭結(jié)點指向的首元結(jié)點(phead->next=phead->next->next),插入只改變尾節(jié)點的(pnode為新插入結(jié)點,pend->next=pnode;pend=pnode,即可)
2.頭結(jié)點,首元結(jié)點,尾節(jié)點有不明白的可參考我的上一篇博客。
3.總體來說,鏈隊列的實現(xiàn)比數(shù)組隊列的實現(xiàn)要方便,而且實用。
4.結(jié)構(gòu)體里面也可以有構(gòu)造器;
5.第一個元素一定是插在初始化的pend->next;所以在初始化的時候一定要讓phead=pend,達(dá)到讓phead指向首元元素的目的。
6.c++中取反用!;不是~,切記切記切記;
二、代碼:
demo092103.cpp
#include<iostream>
#include<stdlib.h>
using namespace
template<class T>
struct Node{Node(T t):value(0),next(nullptr){};Node();T value;Node<T>* next;
}
template<class T>
class Linkqueque{
public:Linkqueque();~Linkqueque();bool isEmpty();int size();void push(T t);bool pop();T front();
private:Node<T>* phead;Node<T>*pend;int count;
};
Linkqueque<T>::Linkqueque(){//此處一定要有phead=pend,因為插入是插在pend的next里,故第一個元素一定在pend->next;因為第一個元素一定在初始化的pend后面,所以初始化的時候一定有phead=pend;讓phead指向第一個元素,即首元元素Node<T>* phead=new Node<T>();pend=phead;count=0;
}
template<class T>
Linkqueque<T>::~Linkqueque(){while(pend->next!=nullptr){Node<T>* pnode=new Node<T>();pnode=pend->next;phead=pend->next;delete pnode;}
}
template<class T>
void Linkqueque<T>::push<T t>{Node<T>* pnode=new Node<T>(t);pend->next=pnode;pend=pnode;count++;
}
template<class T>
bool Linkqueque<T>::pop(){ if(count==0){return false;}else{Node<T>* pnode;pnode=phead->next;phead->next=phead->next->next;delete pnode;count--;return true;}
}
template<class T>
bool Linkqueque<T>::isEmpty(){
return count==0;
}
template<class T>
int Linkqueque<T>::size(){
return count;
}
template<class T>
T Linkqueque<T>::front(){
return (phead->next->vlaue);
}
主函數(shù)代碼
main.cpp
#include<iostream>
#include<stdlib.h>
#include<string>
#include"demo092103.cpp"
using namespace std;
int main(){Linkqueque<string> lqueque;lqueque.push("one");lqueque.push("two");lqueque.push("three");lqueque.push("four");lqueque.push("five");cout<<"隊列大小"<<lqueque.size()<<endl;while(!lqueque.isEmpty()){cout<<lqueque.front()<<endl;lqueque.pop();}system("pause");return 0;
}
三、運(yùn)行結(jié)果:
四、如有錯誤,歡迎指出,一塊交流學(xué)習(xí);
總結(jié)
以上是生活随笔為你收集整理的C++之链队列的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。