写一个顺序队列的插入与删除代码及其主函数
时间: 2024-02-28 08:55:39 浏览: 26
好的,以下是顺序队列的插入与删除代码及其主函数:
```c++
#include <iostream>
using namespace std;
#define MAXSIZE 100 // 定义队列最大长度
typedef struct {
int data[MAXSIZE]; // 队列元素数组
int front; // 队头指针
int rear; // 队尾指针
} SqQueue; // 定义顺序队列类型
// 初始化队列,将队头指针和队尾指针都置为0
void InitQueue(SqQueue &Q) {
Q.front = Q.rear = 0;
}
// 判断队列是否为空
bool IsQueueEmpty(SqQueue Q) {
return Q.front == Q.rear;
}
// 判断队列是否已满
bool IsQueueFull(SqQueue Q) {
return (Q.rear + 1) % MAXSIZE == Q.front;
}
// 入队操作
bool EnQueue(SqQueue &Q, int x) {
if (IsQueueFull(Q)) {
return false;
}
Q.data[Q.rear] = x; // 新元素入队
Q.rear = (Q.rear + 1) % MAXSIZE; // 队尾指针后移一位
return true;
}
// 出队操作
bool DeQueue(SqQueue &Q, int &x) {
if (IsQueueEmpty(Q)) {
return false;
}
x = Q.data[Q.front]; // 记录队头元素
Q.front = (Q.front + 1) % MAXSIZE; // 队头指针后移一位
return true;
}
// 主函数
int main() {
SqQueue Q;
int x;
InitQueue(Q); // 初始化队列
EnQueue(Q, 1); // 入队操作
EnQueue(Q, 2);
EnQueue(Q, 3);
while (!IsQueueEmpty(Q)) { // 出队操作
DeQueue(Q, x);
cout << x << " ";
}
cout << endl;
return 0;
}
```
希望对您有帮助!
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)