循环顺序队列实现代码
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
循环顺序队列实现代码以下是循环顺序队列的实现代码:
```c++
#include <iostream>
using namespace std;
//定义循环顺序队列的类
class CircularQueue
public:
CircularQueue(int capacity);
~CircluarQueue(;
void enqueue(int data);
int dequeue(;
bool isEmpty(;
bool isFull(;
int getFront(;
int getRear(;
private:
int* queue;
int capacity;
int front;
int rear;
};
//初始化循环顺序队列
CircularQueue::CircularQueue(int capacity) this->capacity = capacity;
queue = new int[capacity];
front = -1; // 队列为空时,front指向-1 rear = -1; // 队列为空时,rear指向-1
//销毁循环顺序队列
CircularQueue::~CircularQueu
delete[] queue;
//入队操作
void CircularQueue::enqueue(int data)
//队列已满
if (isFull()
cout << "Queue is full!" << endl;
return;
}
// 队列为空,同时将front指向0
if (isEmpty()
front = 0;
}
//队尾指针循环前进
rear = (rear + 1) % capacity; queue[rear] = data;
//出队操作
int CircularQueue::dequeu
int data;
//队列为空
if (isEmpty()
cout << "Queue is empty!" << endl; return -1;
}
data = queue[front];
//队列中只有一个元素
if (front == rear)
front = -1;
rear = -1;
}
else
front = (front + 1) % capacity; // 队头指针循环前进}
return data;
//判断队列是否为空
bool CircularQueue::isEmpt
return (front == -1 && rear == -1);
//判断队列是否已满
bool CircularQueue::isFul
return ((rear + 1) % capacity == front);
//获取队头元素
int CircularQueue::getFron
if (isEmpty()
cout << "Queue is empty!" << endl;
return -1;
}
return queue[front];
//获取队尾元素
int CircularQueue::getRea
if (isEmpty()
cout << "Queue is empty!" << endl;
return -1;
}
return queue[rear];
int mai
CircularQueue queue(5); // 初始化容量为5的循环顺序队列queue.enqueue(1);
queue.enqueue(2);
queue.enqueue(3);
queue.enqueue(4);
queue.enqueue(5);
cout << "Front: " << queue.getFront( << ", Rear: " << queue.getRear( << endl;
cout << "Dequeue: " << queue.dequeue( << endl;
cout << "Front: " << queue.getFront( << ", Rear: " << queue.getRear( << endl;
queue.enqueue(6);
cout << "Front: " << queue.getFront( << ", Rear: " << queue.getRear( << endl;
return 0;
```
以上是基于C++的循环顺序队列的实现代码。
循环顺序队列通过数组实现,在队尾插入元素,在队头删除元素。
通过维护队头和队尾指针的位置来实现循环队列的性质。
可以通过enqueue操作将元素加入队列,在队满时会出现队满的情况。
可以通过dequeue操作将队头元素删除,并返回被删除的元素值。
同时,可以通过getFront和getRear操作获取队列的队头和队尾元素值。