链表查询最大节点
#include <stdio.h>
#include <stdlib.h>
struct ListNode {
int val;
struct ListNode* next;
};
// 创建链表节点
struct ListNode* createNode(int value) {
struct ListNode* newNode = (struct ListNode*)malloc(sizeof(struct ListNode));
newNode->val = value;
newNode->next = NULL;
return newNode;
}
// 查找链表中的最大节点值
int findMaxNode(struct ListNode* head) {
if (head == NULL) {
return -1; // 如果链表为空,返回一个特殊值表示没有最大值
}
int maxVal = head->val;
struct ListNode* current = head->next;
while (current!= NULL) {
if (current->val > maxVal) {
maxVal = current->val;
}
current = current->next;
}
return maxVal;
}
// 释放链表内存
void freeList(struct ListNode* head) {
struct ListNode* current = head;
while (current!= NULL) {
struct ListNode* next = current->next;
free(current);
current = next;
}
}
int main() {
// 创建链表:1 -> 3 -> 2 -> 5 -> 4
struct ListNode* head = createNode(1);
head->next = createNode(3);
head->next->next = createNode(2);
head->next->next->next = createNode(5);
head->next->next->next->next = createNode(4);
int maxValue = findMaxNode(head);
if (maxValue!= -1) {
printf("链表中的最大节点值为:%d\n", maxValue);
} else {
printf("链表为空,无法找到最大节点值。\n");
}
// 释放链表内存
freeList(head);
return 0;
}
原文地址:https://blog.csdn.net/2302_80782671/article/details/143001569
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!