使用C++创建一个循环队列的完整程序代码,并且编写main函数测试栈的基本功能以及正确性
时间: 2023-07-15 21:13:21 浏览: 42
以下是一个使用C++创建循环队列的完整程序代码:
```cpp
#include <iostream>
using namespace std;
const int MAXSIZE = 10;
class CircularQueue {
private:
int front, rear;
int data[MAXSIZE];
public:
CircularQueue() {
front = rear = 0;
}
bool isFull() {
return (rear + 1) % MAXSIZE == front;
}
bool isEmpty() {
return rear == front;
}
bool enqueue(int x) {
if (isFull()) {
cout << "Queue is full." << endl;
return false;
}
data[rear] = x;
rear = (rear + 1) % MAXSIZE;
return true;
}
bool dequeue(int &x) {
if (isEmpty()) {
cout << "Queue is empty." << endl;
return false;
}
x = data[front];
front = (front + 1) % MAXSIZE;
return true;
}
void print() {
if (isEmpty()) {
cout << "Queue is empty." << endl;
return;
}
cout << "Queue: ";
int i = front;
while (i != rear) {
cout << data[i] << " ";
i = (i + 1) % MAXSIZE;
}
cout << endl;
}
};
int main() {
CircularQueue q;
int x;
q.enqueue(1);
q.enqueue(2);
q.enqueue(3);
q.print();
q.dequeue(x);
cout << "Dequeued item: " << x << endl;
q.print();
q.enqueue(4);
q.enqueue(5);
q.print();
q.enqueue(6);
q.enqueue(7);
q.enqueue(8);
q.enqueue(9);
q.enqueue(10);
q.print();
q.enqueue(11);
return 0;
}
```
在main函数中,我们首先创建了一个循环队列q,并且依次使用enqueue函数将1、2、3加入队列中,并使用print函数打印队列中的元素。然后我们使用dequeue函数将队首元素弹出,并打印出弹出的元素和剩余队列中的元素。接着我们再次使用enqueue函数将4、5加入队列中,并使用print函数打印队列中的元素。然后我们使用enqueue函数依次将6、7、8、9、10加入队列中,并使用print函数打印队列中的元素。最后我们再次使用enqueue函数将11加入队列中,由于队列已满,所以程序会输出"Queue is full."。
通过以上操作,我们可以看到循环队列的基本功能和正确性已经得到验证。