实现循环队列基本操作的完整C语言源代码
时间: 2023-09-03 11:08:13 浏览: 87
循环队列的基本操作的c算法实现
以下是循环队列基本操作的完整C语言源代码:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAX_QUEUE_SIZE 5
typedef struct {
int front;
int rear;
int data[MAX_QUEUE_SIZE];
} Queue;
Queue *createQueue() {
Queue *queue = (Queue *) malloc(sizeof(Queue));
queue->front = -1;
queue->rear = -1;
return queue;
}
int isQueueEmpty(Queue *queue) {
return queue->front == -1 && queue->rear == -1;
}
int isQueueFull(Queue *queue) {
return (queue->rear + 1) % MAX_QUEUE_SIZE == queue->front;
}
void enQueue(Queue *queue, int value) {
if (isQueueFull(queue)) {
printf("Queue is full\n");
return;
} else if (isQueueEmpty(queue)) {
queue->front = 0;
queue->rear = 0;
} else {
queue->rear = (queue->rear + 1) % MAX_QUEUE_SIZE;
}
queue->data[queue->rear] = value;
}
int deQueue(Queue *queue) {
int value;
if (isQueueEmpty(queue)) {
printf("Queue is empty\n");
return -1;
} else if (queue->front == queue->rear) {
value = queue->data[queue->front];
queue->front = -1;
queue->rear = -1;
} else {
value = queue->data[queue->front];
queue->front = (queue->front + 1) % MAX_QUEUE_SIZE;
}
return value;
}
void printQueue(Queue *queue) {
if (isQueueEmpty(queue)) {
printf("Queue is empty\n");
} else {
int i = queue->front;
while (i != queue->rear) {
printf("%d ", queue->data[i]);
i = (i + 1) % MAX_QUEUE_SIZE;
}
printf("%d\n", queue->data[i]);
}
}
int main() {
Queue *queue = createQueue();
enQueue(queue, 1);
enQueue(queue, 2);
enQueue(queue, 3);
enQueue(queue, 4);
enQueue(queue, 5);
enQueue(queue, 6); // should print "Queue is full"
printQueue(queue); // should print "1 2 3 4 5"
deQueue(queue);
deQueue(queue);
deQueue(queue);
printQueue(queue); // should print "4 5"
enQueue(queue, 6);
enQueue(queue, 7);
printQueue(queue); // should print "4 5 6 7"
return 0;
}
```
阅读全文