c++实现寻找单链表中最大值
时间: 2023-06-29 08:03:45 浏览: 51
可以使用以下代码实现单链表中最大值的查找:
```c++
#include <iostream>
using namespace std;
// 定义链表节点结构体
struct ListNode {
int val;
ListNode* next;
ListNode(int x): val(x), next(nullptr) {}
};
int getMax(ListNode* head) {
if (head == nullptr) {
return INT_MIN; // 如果链表为空,则返回最小整数值
}
int maxVal = head->val;
ListNode* cur = head->next;
while (cur != nullptr) {
if (cur->val > maxVal) {
maxVal = cur->val;
}
cur = cur->next;
}
return maxVal;
}
int main() {
// 创建链表 1 -> 3 -> 5 -> 2 -> 4
ListNode* head = new ListNode(1);
head->next = new ListNode(3);
head->next->next = new ListNode(5);
head->next->next->next = new ListNode(2);
head->next->next->next->next = new ListNode(4);
// 查找链表中最大值
int maxVal = getMax(head);
cout << "The maximum value in the linked list is: " << maxVal << endl;
return 0;
}
```
输出结果为:
```
The maximum value in the linked list is: 5
```