理论基础 —— 队列 —— 链队列
生活随笔
收集整理的這篇文章主要介紹了
理论基础 —— 队列 —— 链队列
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
【實現類】
template<class T> struct Node{T data;Node *next; }; template<class T> class linkQueue{ public:linkQueue();~linkQueue();void push(T x);//入隊T pop();//出隊bool empty();//判斷隊列是否為空T getFront();//獲取隊首元素 private:Node<T> *head,*tail; };【構造函數】
template <class T> linkQueue<T>::linkQueue(){Node<T> s=new Node<T>;//創建一個頭結點s->next=NULL;head=tail=s;//隊首與隊尾指針指向頭結點 }【析構函數】
template<class T> linkQueue<T>::~linkQueue(){while(head!=NULL){Node<T> q=head;//暫存要被釋放的結點head=head->next;//first指向要被釋放的結點的下一個結點delete q;//刪除結點} }【入隊】
template <class T> void linkQueue<T>::push(T x){//入隊Node<T> s=new Node<T>;//新申請結點s->data=x;s->next=NULL;tail->next=s;//結點s插到隊尾tail=s; }【出隊】
template <class T> T linkQueue<T>::pop(){//出隊if(head==tail)throw "下溢";Node<T> p=new Node<T>;p=head->next;T x=p->data;//暫存出隊結點head->next=p->next;if(p->next==NULL)//判斷隊列此時是否為空tail=head;delete p;return x; }【判斷是否為空】
template<class T> bool linkQueue<T>::empty(){//判斷隊列是否為空if(head==tail)return true;return false; }【獲取隊首元素】
template<class T> T linkQueue<T>::getFront(){//獲取隊首元素if(head==tail)throw "下溢";return head->next->data; }?
總結
以上是生活随笔為你收集整理的理论基础 —— 队列 —— 链队列的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Ivan and Burgers(CF-
- 下一篇: C++语言基础 —— STL —— 容器