c++实现循环队列的长度并运行结果
时间: 2023-08-04 20:37:24 浏览: 90
循环队列长度的实现代码如下:
```c++
#include<iostream>
using namespace std;
class CircularQueue{
private:
int front; // 队头指针
int rear; // 队尾指针
int size; // 队列长度
int *data; // 队列数组
public:
CircularQueue(int k){
front = 0;
rear = 0;
size = k+1; // 为了区分队空和队满,数组长度要比队列长度多1
data = new int[size];
}
~CircularQueue(){
delete[] data;
}
bool isEmpty(){
return front == rear;
}
bool isFull(){
return (rear+1)%size == front;
}
void enqueue(int value){
if(isFull()){
cout<<"Queue is Full"<<endl;
return;
}
data[rear] = value;
rear = (rear+1)%size;
}
int dequeue(){
if(isEmpty()){
cout<<"Queue is Empty"<<endl;
return -1;
}
int res = data[front];
front = (front+1)%size;
return res;
}
int getLength(){
return (rear-front+size)%size;
}
};
int main(){
CircularQueue cq(3);
cq.enqueue(1);
cq.enqueue(2);
cq.enqueue(3);
cout<<"Length: "<<cq.getLength()<<endl; // 输出队列长度
cq.dequeue();
cout<<"Length: "<<cq.getLength()<<endl;
cq.dequeue();
cout<<"Length: "<<cq.getLength()<<endl;
cq.dequeue();
cout<<"Length: "<<cq.getLength()<<endl;
cq.dequeue();
cout<<"Length: "<<cq.getLength()<<endl;
return 0;
}
```
运行结果如下:
```
Length: 3
Length: 2
Length: 1
Length: 0
Queue is Empty
Length: 0
```
阅读全文