1. 程式人生 > >佇列的順序表實現(C語言)

佇列的順序表實現(C語言)

#include <stdio.h>
#include <stdlib.h>

struct QueueRecord;
typedef struct QueueRecord* Queue;
typedef int ElementType;

#define MinElementSize 10

// 佇列的資料結構
struct QueueRecord
{
    int Capacity;
    int Front;
    int Rear;
    int Size;
    ElementType* Array;
};

// 設定佇列初始值
void MakeEmpty(Queue Q)
{
    Q->Size = 0
; Q->Front = 1; Q->Rear = 0; } //Queue Structure: Front<<<----<<<----Rear Queue CreateQueue(int MaxElements) { Queue Q; if(MaxElements < MinElementSize) { printf("queue size is too small\n"); return NULL; } Q = malloc(sizeof(struct
QueueRecord)); if(Q == NULL) { printf("queue malloc failed\n"); return NULL; } Q->Array = malloc(sizeof(ElementType)*MaxElements); if(Q->Array == NULL) { printf("Q->Array malloc failed\n"); return NULL; } Q->Capacity = MaxElements; MakeEmpty(Q); return
Q; } // 判斷佇列是否為空 int IsEmpty(Queue Q) { return Q->Size == 0; } // 判斷佇列是否為滿 int IsFull(Queue Q) { return Q->Size == Q->Capacity; } // 讓佇列的頭尾迴圈 int Succ(int value, Queue Q) { value++; if(value == Q->Capacity) value = 0; return value; } // 入隊 void Enqueue(ElementType X, Queue Q) { if(IsFull(Q)) { printf("queue is full\n"); return; } Q->Size++; Q->Rear = Succ(Q->Rear, Q); Q->Array[Q->Rear] = X; } // 出隊 void Dequeue(Queue Q) { if(IsEmpty(Q)) { printf("queue is empty.\n"); return; } Q->Size--; Q->Front = Succ(Q->Front, Q); } // 取佇列頭元素,並出隊頭元素 ElementType FrontAndDequeue(Queue Q) { if(IsFull(Q)) { printf("queue is empty.\n"); return 0; } Q->Size--; ElementType tmp = Q->Array[Q->Front]; Q->Front = Succ(Q->Front, Q); return tmp; } void Free(Queue Q) { free(Q->Array); free(Q); } void PrintQueue(Queue Q) { for(int i=Q->Front; i<=Q->Rear; i++) { printf("pos: %d, %d\n",i,Q->Array[i]); } } int main() { Queue Q = CreateQueue(10); for(int i=1;i<=3;i++) { Enqueue(i, Q); } PrintQueue(Q); printf("dequeue\n"); for(int i=1;i<=3;i++) { printf("%d\n",FrontAndDequeue(Q)); } // Dequeue(Q); PrintQueue(Q); return 0; }