要求在vs2022可运行设计一个循环队列的表示和实现的演示程序,其基本操作有初始化队列、判队列空否、入队列、出队列等功能
时间: 2024-02-05 12:04:33 浏览: 88
好的,以下是一个基于循环队列的演示程序,其中包括了初始化队列、判队列空否、入队列、出队列等基本操作。请参考以下代码:
```c++
#include <iostream>
using namespace std;
const int MAXSIZE = 100; // 队列的最大容量
template<class T>
class CircularQueue {
private:
T data[MAXSIZE]; // 存放队列中元素的数组
int front, rear; // 队头指针和队尾指针
public:
CircularQueue() { front = rear = 0; } // 构造函数,初始化队头指针和队尾指针为0
bool IsEmpty() { return front == rear; } // 判断队列是否为空
bool IsFull() { return (rear+1)%MAXSIZE == front; } // 判断队列是否已满
void EnQueue(T x); // 入队列
T DeQueue(); // 出队列
};
template<class T>
void CircularQueue<T>::EnQueue(T x) {
if (IsFull()) // 队列满,则无法入队列
cout << "Error: Queue is Full!" << endl;
else {
rear = (rear+1) % MAXSIZE; // 队尾指针加1
data[rear] = x; // 将元素x入队列
}
}
template<class T>
T CircularQueue<T>::DeQueue() {
if (IsEmpty()) { // 队列空,则无法出队列
cout << "Error: Queue is Empty!" << endl;
return NULL;
}
else {
front = (front+1) % MAXSIZE; // 队头指针加1
T x = data[front]; // 取出队头元素
return x;
}
}
int main() {
CircularQueue<int> Q; // 创建一个整型循环队列Q
Q.EnQueue(1); // 入队列1
Q.EnQueue(2); // 入队列2
Q.EnQueue(3); // 入队列3
while (!Q.IsEmpty()) {
cout << Q.DeQueue() << " "; // 依次出队列并输出
}
cout << endl;
return 0;
}
```
这个程序使用了模板类,可以方便地实现不同类型的队列。你可以在vs2022中编译运行此程序,进行循环队列的基本操作演示。
阅读全文
相关推荐













