1. 程式人生 > 其它 >資料結構之佇列的鏈式表示

資料結構之佇列的鏈式表示

(一)佇列的鏈式表示

若使用者無法估計所用佇列的長度,則宜採用鏈佇列,仍然兩個指標:一個front 頭指標,一個rear尾指標

// 鏈佇列的資料定義
#define MAXQIZE 100 //最大長度
typedef struct Qnode {
    QElemType data;
    stuct Qnode *next;
}QNode,*QuenePtr;

typedef struct {
    QuenePtr front // 隊頭指標
    QuenePtr rear  // 隊尾指標
}LinkQueue

 1.鏈佇列初始化

Status initQueue(LinkQueue &Q) {
    Q.front = Q.rear = (QueuePtr) malloc(sizeof(QNode))    // 建立頭尾指標
    if(!Q.front) exit(OVERFLOW);
    Q.front -> next = NULL                                 // 將頭結點的next置空
    return OK
}

2.銷燬鏈佇列

// 從頭結點開始,依次釋放所有結點
Status Destroy Queue(LinkQueue &Q){
    while(Q.front){
        p = Q.front -> next;
        free(Q.front)
        Q.front = p
    }
}

3.鏈佇列入隊

Status EnQueue(LinkQueue &Q,QElemType e) {
    p = (QueuePtr)malloc(sizeof(QNode))    // 建立新結點
    if(!p) exit (OVERFLOW)
    p->data = e                            // 新結點的資料域 賦值 傳入資料
    p->next = NULL                         // 新結點的next域 賦值 為空
    Q.rear ->next = p                      // 尾結點的next域 賦值 為新結點
    Q.rear = p                             // 將尾指標後移到新結點
}

4.鏈隊出隊

Status DeQueue(LiinkQueue &Q,QElemType &e) {
    if(Q.front == Q.rear) return ERROR        // 判斷出棧之前是否為空
    p = Q.front -> next                       // 將頭指標的next 域賦值給p
    e = p->data                               //  p的資料域賦值給e
    Q.front -> next = p ->next                // 移動頭指標到下一個
    if(Q.rear == p) Q.rear = Q.front
    delete P                                  // 刪除結點p
    return OK
}

5.鏈佇列的頭元素

e = Q.front -> next ->data        // 取頭指標的next域所指向的元素的data域