/*
* 循环队列
*/
#include<stdio.h>
#include<stdlib.h>
typedef int bool;
#define true 1
#define false 0
#define ERROR -1
#define INITSIZE 4
typedef struct {
int *base;
int front;
int rear;
} SqQueue;
SqQueue InitSqQueue() {
SqQueue queue;
SqQueue *p = &queue;
p->base = (int*) malloc(sizeof(int) * INITSIZE);
if (!p->base)
exit(ERROR);
p->front = 0;
p->rear = 0;
return queue;
}
//入队:判断是否满队,这里会浪费一个空间
void SqQueueOffer(SqQueue *queue, int e) {
if ((queue->rear + 1) % INITSIZE == queue->front) {
printf("failed to offer a element\n");
} else {
queue->base[queue->rear] = e;
queue->rear = (queue->rear + 1) % INITSIZE;
}
}
//出队:判断是否为空队列
int SqQueuePoll(SqQueue *queue) {
if (queue->rear == queue->front)
exit(ERROR);
int e = queue->base[queue->front];
queue->front = (queue->front + 1) % INITSIZE;
return e;
}
//判空
bool SqQueueEmpty(SqQueue queue) {
return queue.front == queue.rear ? true : false;
}
//Peek
int SqQueuePeek(SqQueue queue) {
if (queue.front == queue.rear)
exit(ERROR);
return queue.base[queue.front];
}
int main(void) {
SqQueue queue = InitSqQueue();
SqQueueOffer(&queue, 1);
printf("%d\n", SqQueuePeek(queue));
printf("%d\n", SqQueuePoll(&queue));
SqQueueOffer(&queue, 1);
SqQueueOffer(&queue, 2);
SqQueueOffer(&queue, 3);
// 4入队列失败
SqQueueOffer(&queue, 4);
printf("%d\n", SqQueuePoll(&queue));
printf("%d\n", SqQueuePoll(&queue));
printf("%d\n", SqQueuePoll(&queue));
// 出队列失败,程序退出
printf("%d\n", SqQueuePoll(&queue));
return 0;
}
队列的C语言实现:顺序存储
最新推荐文章于 2023-01-17 08:00:52 发布