链表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);
}
相关推荐
(●—●)橘子……4 小时前
记力扣2009:使数组连续的最少操作数 练习理解
数据结构·python·算法·leetcode
GalaxyPokemon4 小时前
LeetCode - 1171.
算法·leetcode·链表
iナナ5 小时前
Java优选算法——位运算
java·数据结构·算法·leetcode
Han.miracle6 小时前
数据结构二叉树——层序遍历&& 扩展二叉树的左视图
java·数据结构·算法·leetcode
筱砚.6 小时前
【数据结构——最小生成树与Kruskal】
数据结构·算法
蒙奇D索大7 小时前
【数据结构】考研数据结构核心考点:平衡二叉树(AVL树)详解——平衡因子与4大旋转操作入门指南
数据结构·笔记·学习·考研·改行学it
im_AMBER8 小时前
数据结构 04 栈和队列
数据结构·笔记·学习
CAU界编程小白10 小时前
数据结构系列之堆
数据结构·c
CoderCodingNo11 小时前
【GESP】C++五级考试大纲知识点梳理, (3-4) 链表-双向循环链表
开发语言·c++·链表
Excuse_lighttime11 小时前
只出现一次的数字(位运算算法)
java·数据结构·算法·leetcode·eclipse