链表OJ---排序链表

https://leetcode.cn/problems/7WHec2/description/

cpp 复制代码
//合并
struct ListNode* merge_link(struct ListNode* head1, struct ListNode* head2) {
    struct ListNode* temhead = malloc(sizeof(struct ListNode));
    temhead->val = 0;
    struct ListNode *tmp = temhead, *cur1 = head1, *cur2 = head2;
    while (cur1 && cur2) {
        if (cur1->val <= cur2->val) {
            tmp->next = cur1;
            cur1 = cur1->next;
        } else {
            tmp->next = cur2;
            cur2 = cur2->next;
        }
        tmp = tmp->next;
    }
    if (cur1) {
        tmp->next = cur1;
    }
    if (cur2) {
        tmp->next = cur2;
    }
    return temhead->next;
}
//分解
struct ListNode* merge_div(struct ListNode* head, struct ListNode* tail) {
    //空结点,因为传参时,我们将NULL当作原链表的尾结点
    if (head == NULL)
        return head;
    //单个结点
    if (head->next == tail)
    {
        head->next = NULL;
        return head;
    }

    //快慢指针找中点
    struct ListNode *slow = head, *fast = head;
    while (fast != tail) {
        slow = slow->next;
        fast = fast->next;
        if (fast != tail) {
            fast = fast->next;
        }
    }
    // slow为中点
    struct ListNode* mid = slow;
    return merge_link(merge_div(head, mid), merge_div(mid, tail));
}

struct ListNode* sortList(struct ListNode* head) {
    return merge_div(head, NULL);
}
相关推荐
学不动CV了1 小时前
数据结构---链表结构体、指针深入理解(三)
c语言·arm开发·数据结构·stm32·单片机·链表
百年孤独_3 小时前
LeetCode 算法题解:链表与二叉树相关问题 打打卡
算法·leetcode·链表
算法_小学生3 小时前
LeetCode 287. 寻找重复数(不修改数组 + O(1) 空间)
数据结构·算法·leetcode
Tanecious.6 小时前
LeetCode 876. 链表的中间结点
算法·leetcode·链表
Wo3Shi4七6 小时前
哈希冲突
数据结构·算法·go
V我五十买鸡腿7 小时前
顺序栈和链式栈
c语言·数据结构·笔记·算法
七灵微8 小时前
数据结构实验习题
数据结构
杰克尼19 小时前
BM5 合并k个已排序的链表
数据结构·算法·链表
xiaolang_8616_wjl19 小时前
c++文字游戏_闯关打怪
开发语言·数据结构·c++·算法·c++20
hqxstudying20 小时前
Java创建型模式---单例模式
java·数据结构·设计模式·代码规范