用c++类设计一个队列类,实现的操作有初始化队列、入队、出队、判队空
时间: 2023-11-25 12:05:49 浏览: 56
好的,下面是一个用C++类来实现队列的示例代码,包含了队列的初始化、入队、出队、判队空等操作:
```c++
#include <iostream>
using namespace std;
const int MAXSIZE = 100; // 队列最大容量
class Queue {
private:
int front; // 队头指针
int rear; // 队尾指针
int data[MAXSIZE]; // 队列数据
public:
Queue(); // 构造函数
bool isEmpty(); // 判队空
bool isFull(); // 判队满
void enQueue(int x); // 入队
void deQueue(); // 出队
void print(); // 输出队列
};
// 构造函数
Queue::Queue() {
front = rear = -1; // 初始化队头和队尾指针
}
// 判队空
bool Queue::isEmpty() {
return front == rear;
}
// 判队满
bool Queue::isFull() {
return rear == MAXSIZE - 1;
}
// 入队
void Queue::enQueue(int x) {
if (isFull()) {
cout << "Queue is full!" << endl;
return;
}
data[++rear] = x;
}
// 出队
void Queue::deQueue() {
if (isEmpty()) {
cout << "Queue is empty!" << endl;
return;
}
++front;
}
// 输出队列
void Queue::print() {
for (int i = front + 1; i <= rear; i++) {
cout << data[i] << " ";
}
}
int main() {
Queue q;
q.enQueue(1);
q.enQueue(2);
q.enQueue(3);
q.print(); // 输出:1 2 3
q.deQueue();
q.print(); // 输出:2 3
return 0;
}
```
以上代码实现了一个基本的队列类,包括了队列的初始化、入队、出队、判队空等操作。在 `enQueue` 方法中,当队列已满时,会输出 "Queue is full!" 的提示信息;在 `deQueue` 方法中,当队列已空时,会输出 "Queue is empty!" 的提示信息。