在链队列的模板类中加一个找最大值的函数
时间: 2024-02-29 09:52:31 浏览: 31
好的,我可以为你解答这个问题。以下是一个链队列模板类的示例,其中包括一个名为 `findMax()` 的函数来查找队列中的最大元素:
```cpp
#include <iostream>
#include <cstdlib>
template <typename T>
class Queue {
private:
struct Node {
T data;
Node* next;
Node(const T& d) : data(d), next(nullptr) {}
};
Node* front;
Node* rear;
int size;
public:
Queue() : front(nullptr), rear(nullptr), size(0) {}
~Queue() {
while (!isEmpty()) {
dequeue();
}
}
bool isEmpty() const {
return front == nullptr;
}
int getSize() const {
return size;
}
void enqueue(const T& value) {
Node* newNode = new Node(value);
if (isEmpty()) {
front = rear = newNode;
} else {
rear->next = newNode;
rear = newNode;
}
size++;
}
void dequeue() {
if (isEmpty()) {
std::cerr << "Error: Queue is empty!" << std::endl;
exit(EXIT_FAILURE);
}
Node* temp = front;
front = front->next;
delete temp;
size--;
if (isEmpty()) {
rear = nullptr;
}
}
T getFront() const {
if (isEmpty()) {
std::cerr << "Error: Queue is empty!" << std::endl;
exit(EXIT_FAILURE);
}
return front->data;
}
T getRear() const {
if (isEmpty()) {
std::cerr << "Error: Queue is empty!" << std::endl;
exit(EXIT_FAILURE);
}
return rear->data;
}
T findMax() const {
if (isEmpty()) {
std::cerr << "Error: Queue is empty!" << std::endl;
exit(EXIT_FAILURE);
}
T max = front->data;
Node* temp = front->next;
while (temp != nullptr) {
if (temp->data > max) {
max = temp->data;
}
temp = temp->next;
}
return max;
}
};
```
在这个示例中,`findMax()` 函数首先检查队列是否为空。如果队列为空,则函数输出错误消息并退出程序。否则,函数将 `max` 变量初始化为队列的第一个元素,并遍历队列中的所有元素以查找最大值。如果当前元素的值大于 `max`,则将 `max` 更新为当前元素的值。最后,函数返回 `max` 变量的值。
请注意,此示例中的 `findMax()` 函数假定队列中的元素类型 `T` 是可比较的,即可以使用 `>` 运算符来比较元素的大小。如果队列中的元素类型不可比较,则需要修改 `findMax()` 函数以使用适当的比较运算符或函数。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)