为充分利用向量空间,克服上述“假溢出”现象的方法是:将为队列分配的向量空间看成为一个首尾相接的圆环,并称这种队列为循环队列(Circular Queue)
入队时尾指针向前追赶头指针,出队时头指针向前追赶尾指针,故队空和队满时头尾指针均相等。因此,无法通过front=rear来判断队列“空”还是“满”。
☞☞解决此问题的方法是:约定入队前,测试尾指针在循环意义下加1后是否等于头指针,若相等则认为队满。即:
◆ rear所指的单元始终为空。
◆ 循环队列为空:front=rear 。
◆ 循环队列满:(rear+1)%MAX_QUEUE_SIZE =front。
#include<stdio.h>
#include<malloc.h>
#define TOTAL_SPACE 5
typedef struct CircleIntQueue {
int data[TOTAL_SPACE];
int head;
int tail;
}*CircleIntQueuePtr;
CircleIntQueuePtr initQueue() {
CircleIntQueuePtr resultPtr = (CircleIntQueuePtr)malloc(sizeof(struct CircleIntQueue));
resultPtr->head = 0;
resultPtr->tail = 0;
return resultPtr;
}
void enqueue(CircleIntQueuePtr paraPtr, int paraValue) {
if ((paraPtr->tail + 1) % TOTAL_SPACE == paraPtr->head) {
printf("Queue full.\n");
return;
}
paraPtr->data[paraPtr->tail % TOTAL_SPACE] = paraValue;
paraPtr->tail++;
}
int dequeue(CircleIntQueuePtr paraPtr) {
int resultValue;
if (paraPtr->head == paraPtr->tail) {
printf("No element in the queue.\n");
return -1;
}
resultValue = paraPtr->data[paraPtr->head % TOTAL_SPACE];
paraPtr->head++;
return resultValue;
}
void outputLinkQueue(CircleIntQueuePtr paraPtr) {
int i;
if (paraPtr->head == paraPtr->tail) {
printf("Empty queue.\n");
return;
}
printf("Elements in the queue: \n");
for (i = paraPtr->head; i < paraPtr->tail; i++) {
printf("%d ",paraPtr->data[i % TOTAL_SPACE]);
}
printf("\r\n");
}
void testLinkQueue() {
int i = 10;
CircleIntQueuePtr tempPtr = initQueue();
for (; i <16; i++) {
enqueue(tempPtr,i);
}
outputLinkQueue(tempPtr);
for (i = 0; i < 6; i++) {
printf("Dequeue gets %d \n",dequeue(tempPtr));
}
enqueue(tempPtr,8);
outputLinkQueue(tempPtr);
}
int main() {
testLinkQueue();
return 1;
}
运行结果
Queue full.
Queue full.
Elements in the queue:
10 11 12 13
Dequeue gets 10
Dequeue gets 11
Dequeue gets 12
Dequeue gets 13
No element in the queue.
Dequeue gets -1
No element in the queue.
Dequeue gets -1
Elements in the queue:
8