链表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);
}
相关推荐
散11211 小时前
01数据结构-01背包问题
数据结构
消失的旧时光-194311 小时前
Kotlinx.serialization 使用讲解
android·数据结构·android jetpack
Gu_shiwww12 小时前
数据结构8——双向链表
c语言·数据结构·python·链表·小白初步
苏小瀚13 小时前
[数据结构] 排序
数据结构
_不会dp不改名_15 小时前
leetcode_21 合并两个有序链表
算法·leetcode·链表
睡不醒的kun15 小时前
leetcode算法刷题的第三十四天
数据结构·c++·算法·leetcode·职场和发展·贪心算法·动态规划
吃着火锅x唱着歌15 小时前
LeetCode 978.最长湍流子数组
数据结构·算法·leetcode
Whisper_long16 小时前
【数据结构】深入理解堆:概念、应用与实现
数据结构
IAtlantiscsdn16 小时前
Redis7底层数据结构解析
前端·数据结构·bootstrap
我星期八休息16 小时前
深入理解跳表(Skip List):原理、实现与应用
开发语言·数据结构·人工智能·python·算法·list