根据数据结构和类模板知识,定义一个通用队列(先进先出)类并加以实现,编写主函数进行测试;
时间: 2024-03-23 21:37:10 浏览: 41
好的,基于数据结构和类模板知识,我可以为你定义一个通用队列类并加以实现。下面是代码:
```c++
#include <iostream>
template<class T>
class Queue {
private:
T* data;
int size;
int capacity;
int front;
int rear;
public:
Queue(int capacity = 10) {
this->capacity = capacity;
this->size = 0;
this->data = new T[capacity];
this->front = -1;
this->rear = -1;
}
bool empty() {
return this->size == 0;
}
bool full() {
return this->size == this->capacity;
}
int length() {
return this->size;
}
void push(T value) {
if (this->full()) {
std::cout << "The queue is full." << std::endl;
return;
}
this->rear = (this->rear + 1) % this->capacity;
this->data[this->rear] = value;
this->size++;
if (this->front == -1) {
this->front = 0;
}
}
void pop() {
if (this->empty()) {
std::cout << "The queue is empty." << std::endl;
return;
}
this->front = (this->front + 1) % this->capacity;
this->size--;
if (this->empty()) {
this->front = -1;
this->rear = -1;
}
}
T front_value() {
if (this->empty()) {
std::cout << "The queue is empty." << std::endl;
return T();
}
return this->data[this->front];
}
T rear_value() {
if (this->empty()) {
std::cout << "The queue is empty." << std::endl;
return T();
}
return this->data[this->rear];
}
void print() {
if (this->empty()) {
std::cout << "The queue is empty." << std::endl;
return;
}
for (int i = this->front; i != this->rear; i = (i + 1) % this->capacity) {
std::cout << this->data[i] << " ";
}
std::cout << this->data[this->rear] << std::endl;
}
};
int main() {
Queue<int> q(5);
std::cout << "Is the queue empty? " << q.empty() << std::endl;
q.push(1);
q.push(2);
q.push(3);
q.push(4);
q.push(5);
std::cout << "Is the queue full? " << q.full() << std::endl;
q.print();
std::cout << "The front value of queue is " << q.front_value() << std::endl;
std::cout << "The rear value of queue is " << q.rear_value() << std::endl;
q.pop();
q.pop();
q.pop();
q.print();
return 0;
}
```
以上就是一个通用队列类的实现,并在主函数中进行了测试。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![application/msword](https://img-home.csdnimg.cn/images/20210720083327.png)