设计一个主函数对循环队列进行测试。主要功能有:入队操作、出队操作、取对头元素
时间: 2024-10-23 16:17:55 浏览: 42
设计一个主函数用于循环队列的测试,主要包括以下几个步骤:
```c++
#include <iostream>
using namespace std;
// 定义循环队列的结构体(这里简化了实现,实际项目中可能需要更复杂的数据结构)
template <typename T>
class CircularQueue {
private:
int front, rear;
T* queue;
const int capacity;
public:
// 构造函数,初始化队列大小
CircularQueue(int size) : front(0), rear(size - 1), queue(new T[size]), capacity(size) {}
// 入队操作(如果队满则会“溢出”到队首)
void enqueue(T item) {
if ((rear + 1) % capacity == front) {
cout << "Queue is full, cannot enqueue." << endl;
return;
}
rear = (rear + 1) % capacity;
queue[rear] = item;
cout << "Enqueue: " << item << ", Queue: ";
display();
}
// 出队操作(如果队空则返回空值)
T dequeue() {
if (front == rear) {
cout << "Queue is empty, cannot dequeue." << endl;
return T(); // 返回默认构造的空值
}
T item = queue[front];
front = (front + 1) % capacity;
cout << "Dequeue: " << item << ", Queue: ";
display();
return item;
}
// 取队头元素,类似于出队但不会删除
T getFront() {
if (front == rear) {
cout << "Queue is empty, no front element." << endl;
return T(); // 返回默认构造的空值
}
return queue[front];
}
// 显示队列内容
void display() {
for (int i = front; i != rear; i = (i + 1) % capacity)
cout << queue[i] << " ";
cout << endl;
}
~CircularQueue() { delete[] queue; } // 析构函数释放内存
};
int main() {
// 创建循环队列实例,假设大小为5
CircularQueue<int> cq(5);
// 测试基本操作
cq.enqueue(1);
cq.enqueue(2);
cq.enqueue(3);
// 检查队头元素并打印
cout << "Front element: " << cq.getFront() << endl;
// 出队操作并打印结果
int dequeued = cq.dequeue();
cout << "dequeued: " << dequeued << endl;
// 再次尝试出队,这时队列为空
dequeued = cq.dequeue();
if (dequeued == cq.getFront()) {
cout << "Both dequeue and getFront returned empty." << endl;
}
return 0;
}
阅读全文