请设计一个c++程序模拟队列,具备入队、出队、置队列为空、输出队列数据的功能。 (队列容量为10,即最多有10个元素在一个队中。)
时间: 2024-04-30 19:22:03 浏览: 24
以下是一个简单的 C++ 队列模拟程序,实现了入队、出队、判断队列是否为空、输出队列数据等基本功能。队列容量为10。
```c++
#include <iostream>
using namespace std;
const int MAX_SIZE = 10; // 队列容量
class Queue {
private:
int data[MAX_SIZE]; // 队列数据
int front; // 队首指针
int rear; // 队尾指针
public:
Queue() {
front = 0;
rear = 0;
}
// 判断队列是否为空
bool isEmpty() {
return front == rear;
}
// 入队
bool enqueue(int x) {
if (rear == MAX_SIZE) { // 队列已满
return false;
}
data[rear++] = x;
return true;
}
// 出队
bool dequeue(int& x) {
if (isEmpty()) { // 队列为空
return false;
}
x = data[front++];
return true;
}
// 置队列为空
void makeEmpty() {
front = 0;
rear = 0;
}
// 输出队列数据
void printQueue() {
if (isEmpty()) {
cout << "Queue is empty." << endl;
return;
}
cout << "Queue: ";
for (int i = front; i < rear; i++) {
cout << data[i] << " ";
}
cout << endl;
}
};
int main() {
Queue q;
// 测试入队
for (int i = 1; i <= 10; i++) {
if (!q.enqueue(i)) {
cout << "Queue is full." << endl;
break;
}
}
q.printQueue(); // Queue: 1 2 3 4 5 6 7 8 9 10
// 测试出队
int x;
while (q.dequeue(x)) {
cout << "Dequeue: " << x << endl;
q.printQueue();
}
// Dequeue: 1
// Queue: 2 3 4 5 6 7 8 9 10
// Dequeue: 2
// Queue: 3 4 5 6 7 8 9 10
// ...
// 测试置队列为空
q.makeEmpty();
q.printQueue(); // Queue is empty.
return 0;
}
```
相关推荐
![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)