C語言——循環隊列和鏈隊列的基本運算

// 循環隊列
#include <stdio.h> #include "SeqQue.h" // 循環隊列的基本運算 /* const int maxsize = 20; typedef struct cycque { int data[maxsize]; int front, rear; }CycQue; */ // 1. 初始化 void InitQueue(CycQue CQ) { CQ.front = 0; CQ.rear = 0; } // 2. 判斷隊空 int EmptyQueue(CycQue CQ) { if(CQ.rear == CQ.front) return 1; else return 0; } // 3. 入隊列 int EnQueue(CycQue CQ, int x) { if((CQ.rear + 1)%maxsize == CQ.front) { printf("隊列滿\n"); return 0; } else { CQ.rear = (CQ.rear + 1)%maxsize; CQ.data[CQ.rear] = x; return 1; } } // 4. 出隊列 int OutQueue(CyQue CQ) { if(EmptyQueue(CQ)) { printf("隊列空\n"); return 0; } else { CQ.front = (CQ.front + 1)%maxsize; return 1; } } // 5.取隊列首元素 int GetHead(CycQue CQ) { if(EmptyQueue(CQ)) { printf("隊列爲空\n"); return 0; } else { return CQ.data[(CQ.front + 1)%maxsize]; /* 說明:爲了方便操做,規定front指向隊列首元素的前一個單元, rear指向實際的隊列尾元素單元。 */ } } // 循環隊列的基本運算 main() { }

 

鏈隊列spa

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

/*
// 鏈隊列類型定義
typedef struct LinkQueueNode
{
    int data;
    struct LinkQueueNode *next;
}LkQueNode
typedef struct LkQueue
{
    LkQueNode *front, *rear;
}LkQue;
*/

// 1. 隊列的初始化
void InitQueue(LkQue *LQ)
{
    LkQueNode *temp;
    temp = (LkQueNode *)malloc(sizeof(LkQueNode));
    LQ->front = temp;
    LQ->rear = temp;
    (LQ->front)->next = NULL;
}

// 2. 判隊列空
int EmptyQueue(LkQue LQ)
{
    if(LQ.rear == LQ.front)
        return 1;
    else
        return 0;
}

// 3. 入隊列
void EnQueue(LkQue *LQ, int x)
{
    LkQueNode *temp;
    temp = (LkQueNode *)malloc(sizeof(LkQueNode));
    temp->data = x;
    temp->next = NULL;
    (LQ->rear)->next = temp; // 新節點入隊列
    LQ->rear = temp; // 置新的隊列尾節點

}

// 4. 出隊列
int OutQueue(LkQueue *LQ)
{
    LkQueNode *temp;
    if(EmptyQueue(LQ))
    {
        printf("隊列爲空\n");
        return 0;
    }
    else
    {
        temp = LQ->front->next; // 隊列首元素
        (LQ->front)->next = temp->next;

        if(temp->next == NULL)
            LQ->rear = LQ->front; // 無首節點時,front和rear都指向頭節點
        free(temp);
        return 1;
    }
}
相關文章
相關標籤/搜索