查找链表中的最大值
时间: 2023-07-10 21:26:38 浏览: 230
可以遍历整个链表,依次比较每个节点的值,找到最大值即可。具体实现可以参考以下代码:
```
int findMax(ListNode* head) {
int maxVal = INT_MIN;
while (head != nullptr) {
if (head->val > maxVal) {
maxVal = head->val;
}
head = head->next;
}
return maxVal;
}
```
其中,ListNode 是链表节点的定义,val 表示节点的值,next 表示指向下一个节点的指针。函数返回链表中的最大值。
相关问题
c语言链表查找最大值
以下是使用C语言链表查找最大值的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义链表节点结构
struct Node {
int data;
struct Node* next;
};
// 在链表末尾插入节点
void insert(struct Node** head, int value) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node)); newNode->data = value;
newNode->next = NULL;
if (*head == NULL) {
*head = newNode;
} else {
struct Node* current = *head;
while (current->next != NULL) {
current = current->next;
}
current->next = newNode;
}
}
// 查找链表中的最大值
int findMax(struct Node* head) {
if (head == NULL) {
printf("链表为空\n");
return -1;
}
int max = head->data;
struct Node* current = head->next;
while (current != NULL) {
if (current->data > max) {
max = current->data;
}
current = current->next;
}
return max;
}
int main() {
struct Node* head = NULL;
// 插入节点
insert(&head, 100);
insert(&head, 2);
insert(&head, 3);
insert(&head, -2);
insert(&head, -8);
insert(&head, -6);
insert(&head, -9);
insert(&head, -10);
insert(&head, 50);
insert(&head, 2);
insert(&head, -1);
// 查找最大值
int max = findMax(head);
printf("链表中的最大值为:%d\n", max);
return 0;
}
```
c语言查找链表最大值节点,C语言—链表的查找
可以按照以下步骤来查找链表中最大值节点:
1. 定义一个指针变量maxNode,初始值为链表的头节点。
2. 遍历链表,比较每个节点的值和maxNode节点的值,如果当前节点的值大于maxNode节点的值,则将maxNode指向当前节点。
3. 遍历完成后,maxNode指向的节点就是链表中的最大值节点。
下面是代码实现:
```c
typedef struct ListNode {
int val;
struct ListNode* next;
} ListNode;
ListNode* findMaxNode(ListNode* head) {
ListNode* maxNode = head;
ListNode* curNode = head;
while (curNode != NULL) {
if (curNode->val > maxNode->val) {
maxNode = curNode;
}
curNode = curNode->next;
}
return maxNode;
}
```
使用时,只需要调用findMaxNode函数并传入链表的头节点即可:
```c
ListNode* head = createList(); // 创建链表
ListNode* maxNode = findMaxNode(head); // 查找最大值节点
printf("Max value: %d\n", maxNode->val);
```
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.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)