队列和栈是类似的想法,都是比较基础的数据结构,但是越基础的东西越是值得重视。、
下面的实现例程是循环队列,主要增加了一个succ函数来实现循环,也正是这一个函数让整个函数功能更加完整。
操作图示:
QueueRecord.h:
#ifndef QUEUERECORD_H #define QUEUERECORD_H typedef char ElementType; struct QueueRecord; typedef struct QueueRecord *Queue; int IsEmpty(Queue Q); int IsFull(Queue Q); Queue CreatQueue(int MaxQueueSize); void MakeEmpty(Queue Q); void DisposeQueue(Queue Q); static int Succ(Queue Q, int Value);//循环队列的判断函数 void Enqueue(Queue Q, ElementType X); void Dequeue(Queue Q); ElementType Front(Queue Q); ElementType FrontAndDequeue(Queue Q); #endif
SequenceQueue.c:
/*循环队列——主要细节在MakeEmpty那里*/ #include"QueueRecord.h" #include<stdio.h> #include<stdlib.h> #define MinQueueSize (5) struct QueueRecord{ int capacity;//the fixed size of queue int size;//the dynamic size of queue int front; int rear; ElementType *Array; }; int IsEmpty(Queue Q) { return Q->size == 0; } int IsFull(Queue Q) { return Q->capacity == Q->size; } Queue CreatQueue(int MaxQueueSize) { Queue Q; if(MaxQueueSize < MinQueueSize) printf("Queue Size is too small!"); Q = (Queue)malloc(sizeof(struct QueueRecord)); if(Q == NULL) printf("Aallocation failure!"); else { Q->Array = (ElementType*)malloc(sizeof(ElementType) * MaxQueueSize); if(Q->Array == NULL) printf("Aallocation failure!"); else { Q->capacity = MaxQueueSize; MakeEmpty(Q); } } return Q; } void MakeEmpty(Queue Q) { Q->size = 0; Q->rear = 0;//when enquen a element to queue , rear + 1 make rear == front , Q->front = 1; } void DisposeQueue(Queue Q) { if(!IsEmpty(Q)) { free(Q->Array); free(Q); } } //判断是否到队列尾部的函数 static 用来表示只再本程序内 static int Succ(Queue Q, int Value) { if(++Value == Q->capacity) Value = 0; return Value; } void Enqueue(Queue Q, ElementType X) { if(IsFull(Q)) printf("Queue is full!, can't enqueue!\n"); else { Q->rear = Succ(Q, Q->rear);//这里的精妙之处我已无法用英语注释 仔细体会!!! Q->Array[Q->rear] = X; Q->size++; } } void Dequeue(Queue Q) { if(IsEmpty(Q)) printf("Queue is empty!, can't dequeue!\n"); else { Q->front = Succ(Q, Q->front); Q->size--; } } ElementType Front(Queue Q) { if(!IsEmpty(Q)) return Q->Array[Q->front]; printf("Sorry the queue is empty! can't find the front element!\n"); return 0;//return value used to avoid warning! } ElementType FrontAndDequeue(Queue Q) { ElementType FrontElement; if(!IsEmpty(Q)) { FrontElement = Q->Array[Q->front]; Q->size--; Q->front = Succ(Q, Q->front); return FrontElement; } else { printf("Sorry the queue is empty! can't find the front element!\n"); return 0; } }
队列的实现例程精彩之处在succ这个函数的实现与其他教材的 %来实现循环相比个人更喜欢这种方法