编写“可扩充循环队列头文件.h”,其中包含循环队列顺序存储结构及以下基本操作:构造空队列、销毁队列、清空队列、求队列长度、判循环队列空、取队头元素、插入元素、删除元素、遍历队列。再编写“可扩充循环队列主程序.cpp”,调用以上函数。
时间: 2024-09-28 11:07:20 浏览: 79
首先,我们需要创建一个名为`CircularQueue.h`的头文件,用于声明循环队列的数据结构和公共接口:
```cpp
#ifndef CIRCULAR_QUEUE_H
#define CIRCULAR_QUEUE_H
#include <iostream>
template <typename T>
class CircularQueue {
public:
// 构造函数
explicit CircularQueue(size_t capacity);
// 销毁队列
~CircularQueue();
// 清空队列
void clear();
// 判队列是否为空
bool isEmpty() const;
// 返回队列长度
size_t length() const;
// 取队头元素
T front() const;
// 插入元素到队尾
void enqueue(const T& value);
// 删除队头元素
void dequeue();
// 遍历队列
void traverse() const;
private:
T* data; // 存储数据的数组
size_t head; // 队首位置
size_t tail; // 队尾位置
size_t capacity; // 队列容量
};
#endif // CIRCULAR_QUEUE_H
```
接下来,我们将在`CircularQueue.cpp`文件中实现这些函数:
```cpp
#include "CircularQueue.h"
template <typename T>
CircularQueue<T>::CircularQueue(size_t capacity)
{
data = new T[capacity];
head = tail = 0;
capacity_ = capacity;
}
template <typename T>
CircularQueue<T>::~CircularQueue()
{
delete[] data;
}
template <typename T>
void CircularQueue<T>::clear()
{
head = tail = 0;
}
template <typename T>
bool CircularQueue<T>::isEmpty() const
{
return head == tail;
}
template <typename T>
size_t CircularQueue<T>::length() const
{
if (tail > head) {
return tail - head + capacity_;
}
else {
return capacity_ - head + tail;
}
}
template <typename T>
T CircularQueue<T>::front() const
{
if (isEmpty()) {
throw std::runtime_error("Queue is empty");
}
return data[head];
}
template <typename T>
void CircularQueue<T>::enqueue(const T& value)
{
if (length() >= capacity_) {
throw std::runtime_error("Queue is full");
}
data[tail] = value;
tail = (tail + 1) % capacity_;
}
template <typename T>
void CircularQueue<T>::dequeue()
{
if (isEmpty()) {
throw std::runtime_error("Queue is empty");
}
data[head] = T(); // 默认值或空处理,根据需求替换
head = (head + 1) % capacity_;
}
template <typename T>
void CircularQueue<T>::traverse() const
{
for (size_t i = head; i != tail; i = (i + 1) % capacity_) {
std::cout << data[i] << ' ';
}
if (head < tail) {
std::cout << data[head]; // 输出最后一个元素
}
std::cout << std::endl;
}
```
现在,你可以使用`CircularQueue`类在其他`main.cpp`或其他源文件中创建并操作循环队列:
```cpp
#include "CircularQueue.cpp" // 将 .cpp 文件包含进来
int main()
{
CircularQueue<int> queue(5);
// 使用上述提供的函数...
return 0;
}
```
阅读全文