链表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);
}
相关推荐
xiangyun6110 小时前
【408数据结构 03】线性表与顺序表:C++手写SeqList
开发语言·数据结构·c++
爱吃苹果的日记本11 小时前
数据结构第三课补充(空间复杂度)
数据结构·学习
多弗朗皮卡丘11 小时前
数据结构6:队列
c语言·数据结构
xxxiugou12311 小时前
双指针解题秘籍:从入门到精通
c语言·数据结构·c++·算法
Logic10112 小时前
C语言/数据结构位运算题解:异或XOR找出地铁规划中的“独特坐标“——只出现一次的数字
c语言·数据结构·数组·位运算·时间复杂度·算法题·异或性质
沉淀的.晴天12 小时前
FreeRTOS信号量
数据结构·算法
青山木12 小时前
Hot 100 --- 打家劫舍
java·数据结构·算法·leetcode·动态规划
YSL07012413 小时前
线性表和顺序表
数据结构
huang57914714 小时前
数据结构的抽象化与接口复用设计理念4
数据结构
动词ing14 小时前
【学习笔记】数据结构(链表合并 双指针合并有序链表)
数据结构·笔记·学习