链表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);
}
相关推荐
YGGP25 分钟前
吃透 Golang 基础:数据结构之 Map
开发语言·数据结构·golang
weixin_419658311 小时前
数据结构之栈
数据结构
图先1 小时前
数据结构第一章
数据结构
草莓熊Lotso3 小时前
【数据结构初阶】--算法复杂度的深度解析
c语言·开发语言·数据结构·经验分享·笔记·其他·算法
Andrew_Xzw4 小时前
数据结构与算法(快速基础C++版)
开发语言·数据结构·c++·python·深度学习·算法
超的小宝贝5 小时前
数据结构算法(C语言)
c语言·数据结构·算法
凤年徐7 小时前
【数据结构初阶】单链表
c语言·开发语言·数据结构·c++·经验分享·笔记·链表
闪电麦坤9512 小时前
数据结构:递归的种类(Types of Recursion)
数据结构·算法
小熊猫写算法er13 小时前
终极数据结构详解:从理论到实践
数据结构
-qOVOp-14 小时前
408第一季 - 数据结构 - 栈与队列的应用
数据结构