循环队列初始化,入队,出队,取对头元素和求队长算法实现的程序
时间: 2023-06-04 14:06:02 浏览: 190
非常感谢您的提问。关于循环队列初始化、入队、出队、取队头元素以及求队长的算法实现,我可以为您提供一些相关的代码示例和解释。以下是一个简单的循环队列的实现:
```C++
#include <iostream>
using namespace std;
#define MAXSIZE 100
typedef struct {
int data[MAXSIZE];
int front, rear;
} Queue;
void InitQueue(Queue& Q) {
Q.front = Q.rear = 0;
}
bool QueueEmpty(Queue& Q) {
return (Q.front == Q.rear);
}
bool QueueFull(Queue& Q) {
return ((Q.rear + 1) % MAXSIZE == Q.front);
}
bool EnQueue(Queue& Q, int x) {
if (QueueFull(Q)) {
return false;
}
Q.data[Q.rear] = x;
Q.rear = (Q.rear + 1) % MAXSIZE;
return true;
}
bool DeQueue(Queue& Q, int& x) {
if (QueueEmpty(Q)) {
return false;
}
x = Q.data[Q.front];
Q.front = (Q.front + 1) % MAXSIZE;
return true;
}
bool GetHead(Queue& Q, int& x) {
if (QueueEmpty(Q)) {
return false;
}
x = Q.data[Q.front];
return true;
}
int QueueLength(Queue& Q) {
return (Q.rear - Q.front + MAXSIZE) % MAXSIZE;
}
int main() {
Queue Q;
InitQueue(Q);
EnQueue(Q, 1);
EnQueue(Q, 2);
EnQueue(Q, 3);
EnQueue(Q, 4);
EnQueue(Q, 5);
int x;
DeQueue(Q, x);
GetHead(Q, x);
cout << "Length: " << QueueLength(Q) << endl;
return 0;
}
```
在这个代码中,我们首先定义了一个结构体 `Queue` 来表示一个循环队列,其中包含一个大小为 `MAXSIZE` 的数组 `data` 和两个指针 `front` 和 `rear` 。`front` 表示队头指针,`rear` 表示队尾指针。这个队列可以容纳 `MAXSIZE-1` 个元素。
接着我们实现了五个操作:
- `InitQueue` 用来初始化队列。
- `QueueEmpty` 判断队列是否为空。
- `QueueFull` 判断队列是否已满。
- `EnQueue` 将元素入队。
- `DeQueue` 将元素从队列中出队。
- `GetHead` 获取队头元素。
- `QueueLength` 获取队列长度。
在 main 函数中,我们首先初始化队列,并依次将元素 1~5 入队。接着我们将队列中的第一个元素出队,并获取当前队头的元素值。最后我们输出了当前队列的长度。
希望这个程序可以帮助到您。如有任何问题,请随时与我交流。
阅读全文
相关推荐












