數據結構與算法——鏈隊列

總結鏈隊列

什麼是鏈隊?

  隊列的鏈式存儲結構稱爲鏈隊列。鏈隊也有兩個指針,隊頭指針和隊尾指針,這樣隊頭刪除和隊尾插入操作就會很方便,鏈式隊列一般像單鏈表一樣,有一個頭結點。

圖示:


具體實現:

<span style="font-family:Courier New;font-size:14px;">#include <iostream>

using namespace std;
template <class T>
struct Node {
    T data;
    struct Node<T> *next;
};

template<class T>
class LinkQueue {
private:
    Node<T> *front;  //隊頭指針
    Node<T> *rear;   //隊尾指針
public:
    LinkQueue() {
        front = rear = new Node<T>;  //建立頭結點 使其隊頭指針、隊尾指針均指向該頭結點
        front->next = NULL;
    }
    ~LinkQueue();
    void EnQueue(T x);   //入隊
    T DeQueue();         //出隊
    T GetFront();        //得到隊頭元素
    bool IsEmpty() {    //判斷隊列是否爲空
        return front==rear?true:false;
    }
    void Print();       //遍歷隊列
};

template <class T>
void LinkQueue<T>::EnQueue(T x) {
    rear->next = new Node<T>;
    rear = rear->next;
    rear->data = x;
    rear->next = NULL;
}

template<class T>
void LinkQueue<T>::Print() {
    if(IsEmpty()) throw "空隊列異常";
    Node<T> *s = front->next;  //工作指針 指向第一個結點
    while(s) {
        cout<<s->data<<" ";
        s= s->next;
    }
    cout<<endl;
}

/**
    析構函數 釋放節點空間
    此處實現的方式是 從頭結點開始挨個釋放
    先將要釋放結點的下一個節點地址賦值給一個指針,
    因爲是有尾指針,所有直接可用尾指針,否則應該有一個臨時工作指針
    然後釋放該結點,再使頭指針指向釋放掉的結點的後繼結點,循環執行。
*/
template <class T>
LinkQueue<T>::~LinkQueue() {
    while(front) {
        rear = front->next;
        delete front;
        front =rear;
    }
}

template <class T>
T LinkQueue<T>::DeQueue() {
    Node<T> *s = front->next;  //保存隊頭元素指針
    if(!s) throw "下溢異常";
    front->next = s->next;    //將隊頭出棧
    T x = s->data;           //保存隊頭元素
    delete s;
    if(!(front->next))  //若出隊後 隊列爲空,則修改隊尾指針 指向頭結點
       rear = front;
    return x;
}

template <class T>
T LinkQueue<T>::GetFront() {
    if(IsEmpty()) throw "隊空異常";
    return front->next->data;
}

int main()
{
    LinkQueue<int>linkQueue;
    for(int i=0;i<5;i++) {
        linkQueue.EnQueue(i);
    }
    linkQueue.Print();
    linkQueue.EnQueue(8);
    linkQueue.Print();
    cout<<"出棧"<<endl;
    cout<<linkQueue.DeQueue()<<"出棧"<<endl;
    linkQueue.Print();
    cout<<"對頭元素爲:"<<linkQueue.GetFront()<<endl;
    return 0;
}
</span>


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章