1. 程式人生 > >資料結構之自建演算法庫——鏈隊(鏈式佇列)

資料結構之自建演算法庫——鏈隊(鏈式佇列)

按照“0207將演算法變程式”[視訊]部分建議的方法,建設自己的專業基礎設施演算法庫。

鏈隊演算法庫採用程式的多檔案組織形式,包括兩個檔案:
  
  1.標頭檔案:liqueue.h,包含定義鏈隊資料結構的程式碼、巨集定義、要實現演算法的函式的宣告;

#ifndef LIQUEUE_H_INCLUDED
#define LIQUEUE_H_INCLUDED

typedef char ElemType;
typedef struct qnode
{
    ElemType data;
    struct qnode *next;
} QNode;        //鏈隊資料結點型別定義
typedef struct { QNode *front; QNode *rear; } LiQueue; //鏈隊型別定義 void InitQueue(LiQueue *&q); //初始化鏈隊 void DestroyQueue(LiQueue *&q); //銷燬鏈隊 bool QueueEmpty(LiQueue *q); //判斷鏈隊是否為空 int QueueLength(LiQueue *q); //返回佇列中資料元素個數 void enQueue(LiQueue *&q,ElemType e); //入隊 bool deQueue(LiQueue *&q,ElemType &e); //出隊
#endif // LIQUEUE_H_INCLUDED

  2.原始檔:liqueue.cpp,包含實現各種演算法的函式的定義

#include <stdio.h>
#include <malloc.h>
#include "liqueue.h"

void InitQueue(LiQueue *&q)  //初始化鏈隊
{
    q=(LiQueue *)malloc(sizeof(LiQueue));
    q->front=q->rear=NULL;
}
void DestroyQueue(LiQueue *&q)  //銷燬鏈隊
{
    QNode *
p=q->front,*r; //p指向隊頭資料節點 if (p!=NULL) //釋放資料節點佔用空間 { r=p->next; while (r!=NULL) { free(p); p=r; r=p->next; } } free(p); free(q); //釋放鏈隊節點佔用空間 } bool QueueEmpty(LiQueue *q) //判斷鏈隊是否為空 { return(q->rear==NULL); } int QueueLength(LiQueue *q) //返回佇列中資料元素個數 { int n=0; QNode *p=q->front; while (p!=NULL) { n++; p=p->next; } return(n); } void enQueue(LiQueue *&q,ElemType e) //入隊 { QNode *p; p=(QNode *)malloc(sizeof(QNode)); p->data=e; p->next=NULL; if (q->rear==NULL) //若鏈隊為空,則新節點是隊首節點又是隊尾節點 q->front=q->rear=p; else { q->rear->next=p; //將*p節點鏈到隊尾,並將rear指向它 q->rear=p; } } bool deQueue(LiQueue *&q,ElemType &e) //出隊 { QNode *t; if (q->rear==NULL) //佇列為空 return false; t=q->front; //t指向第一個資料節點 if (q->front==q->rear) //佇列中只有一個節點時 q->front=q->rear=NULL; else //佇列中有多個節點時 q->front=q->front->next; e=t->data; free(t); return true; }

  3.在同一專案(project)中建立一個原始檔(如main.cpp),編制main函式,完成相關的測試工作。 例:

#include <stdio.h>
#include "liqueue.h"

int main()
{
    ElemType e;
    LiQueue *q;
    printf("(1)初始化鏈隊q\n");
    InitQueue(q);
    printf("(2)依次進鏈隊元素a,b,c\n");
    enQueue(q,'a');
    enQueue(q,'b');
    enQueue(q,'c');
    printf("(3)鏈隊為%s\n",(QueueEmpty(q)?"空":"非空"));
    if (deQueue(q,e)==0)
        printf("隊空,不能出隊\n");
    else
        printf("(4)出隊一個元素%c\n",e);
    printf("(5)鏈隊q的元素個數:%d\n",QueueLength(q));
    printf("(6)依次進鏈隊元素d,e,f\n");
    enQueue(q,'d');
    enQueue(q,'e');
    enQueue(q,'f');
    printf("(7)鏈隊q的元素個數:%d\n",QueueLength(q));
    printf("(8)出鏈隊序列:");
    while (!QueueEmpty(q))
    {
        deQueue(q,e);
        printf("%c ",e);
    }
    printf("\n");
    printf("(9)釋放鏈隊\n");
    DestroyQueue(q);
    return 0;
}