1. 程式人生 > >連結串列實現佇列

連結串列實現佇列

這次寫的還算正規,稍微壓縮了一下程式碼,但是不影響閱讀

畫個圖幫助理解:

F->0->0->0<-R

第一個0不存資料 

#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
typedef int Elementype;//資料型別
//節點結構
typedef struct Node{
    Elementype Element;//資料域
    struct Node * Next;
}NODE,*PNODE;

//    定義佇列結構體
typedef struct QNode {
    PNODE Front;//隊頭
    PNODE Rear;//隊尾
} Queue, *PQueue;

void init(PQueue queue)//初始化
{//頭尾指向同一記憶體空間//頭結點,不存資料
    queue->Front = queue->Rear = (PNODE)malloc(sizeof(NODE));
    queue->Front->Next = NULL;//頭結點指標為空
}

int isEmpty(PQueue queue)//判空·
{
    if(queue->Front == queue->Rear)return 1;
    return 0;
}

void insert(PQueue queue,Elementype data)//入隊
{
    PNODE P = (PNODE)malloc(sizeof(NODE));//初始化
    P->Element = data;
    P->Next = NULL;
    queue->Rear->Next = P;//入隊
    queue->Rear = P;
}

void delete(PQueue queue,int * val)//出隊,用val返回值
{
    if(isEmpty(queue))printf("隊空");
    else
    {
        PNODE  P = queue->Front->Next;//前一元素
        *val = P->Element;//記錄值
        queue->Front->Next = P->Next;//出隊
        //注意一定要加上判斷,手動模擬一下就明白了
        if(P==queue->Rear)queue->Front=queue->Rear;
        free(P);//注意釋放
        P = NULL;
    }
}

void destroy(PQueue queue)//釋放
{
    //從頭開始刪
    while(queue->Front != NULL)//起臨時指標作用,無需再用別的空間
    {
        queue->Rear = queue->Front->Next;
        free(queue->Front);
        queue->Front = queue->Rear;
    }
}
//測試
int main(void)
{
    int i;
    int e;
    Queue a;
    PQueue queue=&a;
    init(queue);
    for(i=0;i<10;i++)
        insert(queue,i);
    while(!isEmpty(queue))//遍歷
    {
        delete(queue,&e);
        printf("%d ",e);
    }
    if(isEmpty(queue))printf("1\n");
    delete(queue,&e);
    destroy(queue);
}