C++如何创造循环队列
时间: 2024-06-13 16:03:33 浏览: 14
在C++中,可以使用数组来实现循环队列。循环队列是一种特殊的队列,它可以在固定大小的数组中实现队列的基本操作,如入队和出队。下面是一个简单的循环队列的实现:
```c++
#include <iostream>
using namespace std;
const int MAX_SIZE = 5; // 队列的最大容量
class CircularQueue {
private:
int front; // 队头指针
int rear; // 队尾指针
int data[MAX_SIZE]; // 存储队列元素的数组
public:
CircularQueue() {
front = rear = 0; // 初始化队头和队尾指针
}
bool isEmpty() {
return front == rear; // 判断队列是否为空
}
bool isFull() {
return (rear + 1) % MAX_SIZE == front; // 判断队列是否已满
}
void enqueue(int x) {
if (isFull()) {
cout << "Queue is full!" << endl;
return;
}
data[rear] = x; // 将元素插入队尾
rear = (rear + 1) % MAX_SIZE; // 更新队尾指针
}
int dequeue() {
if (isEmpty()) {
cout << "Queue is empty!" << endl;
return -1;
}
int x = data[front]; // 取出队头元素
front = (front + 1) % MAX_SIZE; // 更新队头指针
return x;
}
void print() {
if (isEmpty()) {
cout << "Queue is empty!" << endl;
return;
}
cout << "Queue: ";
int i = front;
while (i != rear) {
cout << data[i] << " ";
i = (i + 1) % MAX_SIZE;
}
cout << endl;
}
};
int main() {
CircularQueue q;
q.enqueue(1);
q.enqueue(2);
q.enqueue(3);
q.print(); // Queue: 1 2 3
q.dequeue();
q.print(); // Queue: 2 3
q.enqueue(4);
q.enqueue(5);
q.print(); // Queue: 2 3 4 5
q.enqueue(6); // Queue is full!
return 0;
}
```
在上面的代码中,我们使用了一个数组来存储队列元素,使用front和rear两个指针来表示队头和队尾的位置。当队列为空时,front和rear指向同一个位置;当队列已满时,rear指向的位置是不能存储元素的,因此需要使用取模运算将rear指针限制在数组范围内。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)