编写程序,实现顺序队列的创建、入队和出队等基本操作算法
时间: 2024-05-12 22:14:57 浏览: 22
以下是顺序队列的基本操作算法,使用 C 语言实现:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 100 // 队列最大长度
// 队列结构体定义
typedef struct {
int data[MAXSIZE]; // 队列元素数组
int front; // 队头指针
int rear; // 队尾指针
} SqQueue;
// 初始化队列
void InitQueue(SqQueue *Q) {
Q->front = Q->rear = 0;
}
// 判断队列是否为空
int IsEmpty(SqQueue Q) {
return Q.front == Q.rear;
}
// 判断队列是否已满
int IsFull(SqQueue Q) {
return (Q.rear + 1) % MAXSIZE == Q.front;
}
// 入队
void EnQueue(SqQueue *Q, int x) {
if (IsFull(*Q)) {
printf("Queue is full.\n");
return;
}
Q->data[Q->rear] = x;
Q->rear = (Q->rear + 1) % MAXSIZE;
}
// 出队
void DeQueue(SqQueue *Q, int *x) {
if (IsEmpty(*Q)) {
printf("Queue is empty.\n");
return;
}
*x = Q->data[Q->front];
Q->front = (Q->front + 1) % MAXSIZE;
}
// 遍历队列并输出所有元素
void TraverseQueue(SqQueue Q) {
if (IsEmpty(Q)) {
printf("Queue is empty.\n");
return;
}
int i = Q.front;
while (i != Q.rear) {
printf("%d ", Q.data[i]);
i = (i + 1) % MAXSIZE;
}
printf("\n");
}
int main() {
SqQueue Q;
int x;
InitQueue(&Q);
// 入队
EnQueue(&Q, 1);
EnQueue(&Q, 2);
EnQueue(&Q, 3);
EnQueue(&Q, 4);
EnQueue(&Q, 5);
// 遍历队列并输出所有元素
TraverseQueue(Q); // 1 2 3 4 5
// 出队
DeQueue(&Q, &x);
printf("DeQueue: %d\n", x); // DeQueue: 1
// 遍历队列并输出所有元素
TraverseQueue(Q); // 2 3 4 5
return 0;
}
```
以上代码实现了顺序队列的创建、入队、出队等基本操作算法。
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)