链表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);
}
相关推荐
GrowingIO技术社区2 小时前
CDP、行为分析、归因与营销自动化有什么区别?
数据结构·数据挖掘·数据分析
GrowingIO技术社区2 小时前
实时标签怎样验收?从数据更新到分群可用
数据结构·数据挖掘·数据分析
Nuanyt17 小时前
LeetCode Hot 100 链表专题(五)· 2 题(Java)
java·算法·leetcode·链表
老师我太想进步了20261 天前
【数据结构-3】算法美学之降复杂度
数据结构·算法
w_zero_one2 天前
算法--构造
java·数据结构·算法
lisw052 天前
互联网上的数据结构可视化!
数据结构·信息可视化
老师我太想进步了20262 天前
【数据结构-1】例解算法复杂度
数据结构·算法
YSL0701242 天前
一文通关-----排序
数据结构·算法
夜不会漫长3 天前
C++:红黑树
数据结构·算法
冻柠檬飞冰走茶3 天前
PTA刷题集之Airline Routes(C语言实现)
c语言·开发语言·数据结构·算法