链表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);
}
相关推荐
码少女16 分钟前
数据结构——希尔排序
数据结构·排序算法
星子yu1 小时前
【学习】怎么学好数据结构
数据结构·学习
chh5633 小时前
C++--list
开发语言·数据结构·c++·学习·算法·list
东华万里4 小时前
第36篇: 数据结构核心:栈与队列深度解析
c语言·数据结构·算法·大学生专区
Database_Cool_4 小时前
实时计数器/排行榜首选:阿里云 Tair 高并发数据结构实践
数据结构·数据库·阿里云·云计算
变量未定义~5 小时前
ST表-龙骑士军团【算法赛】
数据结构·算法
Yang_jie_035 小时前
笔记:数据结构(循环队列相关判断条件)
数据结构·笔记
Hesionberger6 小时前
快速求解完全平方数的最少数量
开发语言·数据结构·python·算法·leetcode·c#
奋发向前wcx17 小时前
P2590 树的统计 题目解析
数据结构·算法·深度优先
额鹅恶饿呃19 小时前
C语言中的数据结构和变量
c语言·数据结构·算法