目录
一、定义结构体
typedef struct CircleIntQueue{
int data[TOTAL_SPACE];
int head;
int tail;
}*CircleIntQueuePtr;
二、初始化队列
CircleIntQueuePtr initQueue() {
CircleIntQueuePtr resultPtr = (CircleIntQueuePtr)malloc(sizeof(CircleIntQueuePtr));
resultPtr->head = 0;
resultPtr->tail = 0;
return resultPtr;
}
三、排队
// 排队
void enqueue(CircleIntQueuePtr paraPtr, int paraValue) {
// 判断队列是否已满
if ((paraPtr->tail + 1) % TOTAL_SPACE == paraPtr->head) {
printf("队列已满\r\n");
return;
}
paraPtr->data[paraPtr->tail % TOTAL_SPACE] = paraValue;
paraPtr->tail++;
}
四、出列
// 出列
int dequeue(CircleIntQueuePtr paraPtr) {
int resultValue;
if (paraPtr->head == paraPtr->tail) {
printf("没有元素在队列中\r\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("队列为空");
return;
}
printf("元素在队列中:");
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("元素地址为:%d 出列得到 %d\r\n",i,dequeue(tempPtr));
}
enqueue(tempPtr, 8);
outputLinkQueue(tempPtr);
}
七、完整代码
#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(CircleIntQueuePtr));
resultPtr->head = 0;
resultPtr->tail = 0;
return resultPtr;
}
// 排队
void enqueue(CircleIntQueuePtr paraPtr, int paraValue) {
// 判断队列是否已满
if ((paraPtr->tail + 1) % TOTAL_SPACE == paraPtr->head) {
printf("队列已满\r\n");
return;
}
paraPtr->data[paraPtr->tail % TOTAL_SPACE] = paraValue;
paraPtr->tail++;
}
// 出列
int dequeue(CircleIntQueuePtr paraPtr) {
int resultValue;
if (paraPtr->head == paraPtr->tail) {
printf("没有元素在队列中\r\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("队列为空");
return;
}
printf("元素在队列中:");
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("元素地址为:%d 出列得到 %d\r\n",i,dequeue(tempPtr));
}
enqueue(tempPtr, 8);
outputLinkQueue(tempPtr);
}
int main(){
testLinkQueue();
return 1;
}
八、运行结果
九、总结及心得
当头指针等于尾指针时,无法判断队列为空还是已满,此时有两种处理方式:
1.通过多加一个空间来解决,如上述所示只需判断当 (paraPtr->tail + 1) % TOTAL_SPACE == paraPtr->head时,队列已满,而当paraPtr->head == paraPtr->tail时说明队列为空。
2.通过定义一个size变量记录队列的元素个数,size == 0就是空,size == 数组长度就是满。