队列:C语言实现 #include <stdio.h> #include <stdlib.h> #define QueueIsEmpty(arg) (arg->Size <= 0) #define QueueIsFull(arg) (arg->Size == arg->Capacity) /*判断是否为空或为满。宏定义,函数调销太大。 队列使用Size和Capacity显式的判断是否空或满。*/ typedef struct queue_tag { int Size ; //记录队列中有多少个元素 int Rear ; //队列尾 int Front ; //队列头 int Capacity ; //队列的长度 int *Array ; //元素数组 }*Queue ; Queue CreatQueue(int NumVertex) { Queue Q ; //alloc memory and detect error分配内存并检测错误 Q = calloc(1, sizeof(struct queue_tag)) ; if(!Q){ fprintf(stderr, "Out of space!\n"); exit(1) ; } Q->Array = calloc(NumVertex, sizeof(int)) ; if(!Q->Array){ fprintf(stderr,"Out of space!\n"); exit(1) ; } //初始化队列 Q->Size = 0 ; Q->Rear = 0 ; Q->Front= 1 ; Q->Capacity = NumVertex ; return Q ; } int Dequeue(Queue Q) { int Result ; if(!QueueIsEmpty(Q)) { Result = Q->Array[Q->Front++] ; //回绕队列,当Front到达数组尾时,让Front回绕到数组0(头)处 if(Q->Front == Q->Capacity) Q->Front = 0 ; Q->Size -- ; return Result ; } else fprintf(stderr, "Queue is Empty!\n") ; } void Enqueue(int e, Queue Q) { if(!QueueIsFull(Q)) { Q->Rear ++ ; //回绕 if(Q->Rear == Q->Capacity) Q->Rear = 0 ; Q->Size ++ ; Q->Array[Q->Rear] = e ; } else fprintf(stderr, "Out of space!\n") ; } void QueueDestory(Queue Q) { if(Q) { if(Q->Array) free(Q->Array) ; free(Q) ; } }