#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 5
typedef struct Queue {
int front;
int rear;
int data[MAXSIZE];
}Queue;
void printQueue(Queue* Q) {
// 要知道队列当前有多少个元素
int length;
if (Q->rear >= Q->front) {
length = Q->rear - Q->front;
}
else {
length = Q->rear + MAXSIZE + 2 - Q->front;
}
int index = Q->front;
for (int i = 0; i < length; i++) {
printf("%d -> ", Q->data[index]);
index = (index + 1) % MAXSIZE;
}
printf("NULL\n");
}
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 1;
}
}
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;
}
}
int main() {
Queue* Q = initQueue();
enQueue(Q, 1);
enQueue(Q, 2);
enQueue(Q, 3);
enQueue(Q, 4);
printQueue(Q);
deQueue(Q);
printQueue(Q);
return 0;
}
c语言 数据结构 循环链表
最新推荐文章于 2024-08-13 14:59:13 发布