欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 新闻 > 焦点 > 链表查询最大节点

链表查询最大节点

2024/10/23 15:23:18 来源:https://blog.csdn.net/2302_80782671/article/details/143001569  浏览:    关键词:链表查询最大节点

#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;
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com