什么是循环队列 及其特点
front:指向队首的编号;rear:指向队尾的编号(数据类型为int)
队列的特点是先进先出,所以新节点插入的位置要在队尾,每插入一个新结点,队尾指针要向后移动一位
循环队列的特点:
1.要牺牲掉一个空间,来判断队列是为空还是满(否则,在初始状态下和在队满状态下,front和rear都指向同一个结点,无法区分)
2.判断逻辑:空:front == rear;
满:(rear + 1)% MAXSIZE == front
初始化
typedef struct Queue {
int front;
int rear;
int data[MAXSIZE];
}Queue;
Queue* initQueue(){
Queue* Q = (Queue*)malloc(sizeof(Queue));
Q->front = Q->rear = 0;
return Q;
}
插入(要先判断是否为满)
int isFull(Queue* Q) {
if ((Q->rear + 1) % MAXSIZE == Q->front)
return 1;
else
return 0;
}
int enQueue(Queue* Q, int data) {
if (isFull(Q))
return 0;//插入失败
else {
Q->data[Q->rear] = data;
Q->rear = (Q->rear + 1) % MAXSIZE;
return data;
}
}
删除(要先判断是否为空)
int isEmpty(Queue* Q) {
if (Q->front == Q->rear)
return 1;
else
return 0;
}
int deQueue(Queue* Q) {
if (isEmpty(Q))
return 0;//删除失败
else {
int data = Q->data[Q->front];
Q->front = (Q->front + 1) % MAXSIZE;
return data;
}
}
打印
void printQueue(Queue* Q) {
int index = Q->front;
//打印前要先知道队列中元素的个数
int lenth = (Q->rear - Q->front + MAXSIZE) % MAXSIZE;
for (int i = 0; i < lenth; i++) {
printf("%d->", Q->data[(index + i) % MAXSIZE]);
}
printf("NULL\n");
}
检验(主函数)
int main(){
Queue* Q = initQueue();
enQueue(Q, 1);
enQueue(Q, 2);
enQueue(Q, 3);
enQueue(Q, 4);
printQueue(Q);
deQueue(Q);
printQueue(Q);
}
完整源代码
#include"headfile.h"
#define MAXSIZE 5
typedef struct Queue {
int front;
int rear;
int data[MAXSIZE];
}Queue;
Queue* initQueue(){
Queue* Q = (Queue*)malloc(sizeof(Queue));
Q->front = Q->rear = 0;
return Q;
}
int isFull(Queue* Q) {
if ((Q->rear + 1) % MAXSIZE == Q->front)
return 1;
else
return 0;
}
int enQueue(Queue* Q, int data) {
if (isFull(Q))
return 0;//插入失败
else {
Q->data[Q->rear] = data;
Q->rear = (Q->rear + 1) % MAXSIZE;
return data;
}
}
int isEmpty(Queue* Q) {
if (Q->front == Q->rear)
return 1;
else
return 0;
}
int deQueue(Queue* Q) {
if (isEmpty(Q))
return 0;//删除失败
else {
int data = Q->data[Q->front];
Q->front = (Q->front + 1) % MAXSIZE;
return data;
}
}
void printQueue(Queue* Q) {
int index = Q->front;
//打印前要先知道队列中元素的个数
int lenth = (Q->rear - Q->front + MAXSIZE) % MAXSIZE;
for (int i = 0; i < lenth; i++) {
printf("%d->", Q->data[(index + i) % MAXSIZE]);
}
printf("NULL\n");
}
int main(){
Queue* Q = initQueue();
enQueue(Q, 1);
enQueue(Q, 2);
enQueue(Q, 3);
enQueue(Q, 4);
printQueue(Q);
deQueue(Q);
printQueue(Q);
}