用C语言设计一个顺序循环列表,操作包括初始化入队列出队列
时间: 2024-04-30 15:23:04 浏览: 114
以下是用C语言实现一个顺序循环列表的示例代码,包括初始化、入队列、出队列等操作:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 10 // 定义最大容量为10
typedef struct {
int data[MAX_SIZE];
int front; // 队头指针
int rear; // 队尾指针
int length; // 队列长度
} SeqQueue;
// 初始化队列
void InitQueue(SeqQueue* Q) {
Q->front = 0;
Q->rear = 0;
Q->length = 0;
}
// 判断队列是否为空
int IsEmpty(SeqQueue* Q) {
return Q->length == 0;
}
// 判断队列是否已满
int IsFull(SeqQueue* Q) {
return Q->length == MAX_SIZE;
}
// 入队列
int EnQueue(SeqQueue* Q, int x) {
if (IsFull(Q)) {
printf("Error: Queue is full!\n");
return 0;
}
Q->data[Q->rear] = x;
Q->rear = (Q->rear + 1) % MAX_SIZE;
Q->length++;
return 1;
}
// 出队列
int DeQueue(SeqQueue* Q, int* x) {
if (IsEmpty(Q)) {
printf("Error: Queue is empty!\n");
return 0;
}
*x = Q->data[Q->front];
Q->front = (Q->front + 1) % MAX_SIZE;
Q->length--;
return 1;
}
int main() {
SeqQueue Q;
InitQueue(&Q);
// 入队列
EnQueue(&Q, 1);
EnQueue(&Q, 2);
EnQueue(&Q, 3);
// 出队列
int x;
DeQueue(&Q, &x);
printf("DeQueue: %d\n", x);
DeQueue(&Q, &x);
printf("DeQueue: %d\n", x);
// 再入队列
EnQueue(&Q, 4);
EnQueue(&Q, 5);
// 出队列
DeQueue(&Q, &x);
printf("DeQueue: %d\n", x);
DeQueue(&Q, &x);
printf("DeQueue: %d\n", x);
return 0;
}
```
运行结果:
```
DeQueue: 1
DeQueue: 2
DeQueue: 3
DeQueue: 4
```
阅读全文
相关推荐
















