链表OJ---排序链表

https://leetcode.cn/problems/7WHec2/description/

 

//合并
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);
}

相关推荐

  1. 排序

    2024-01-25 15:46:01       7 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-01-25 15:46:01       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-01-25 15:46:01       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-01-25 15:46:01       19 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-01-25 15:46:01       20 阅读

热门阅读

  1. art-template, node_modules doesn‘t exist or is not a directory

    2024-01-25 15:46:01       32 阅读
  2. [Python进阶] Python中使用正则表达式

    2024-01-25 15:46:01       32 阅读
  3. LeetCode解法汇总2865. 美丽塔 I

    2024-01-25 15:46:01       35 阅读
  4. Frida Hook Textview

    2024-01-25 15:46:01       39 阅读
  5. linux 数据包发送介绍

    2024-01-25 15:46:01       33 阅读
  6. docker+selenium+firefox | 我踩过的坑

    2024-01-25 15:46:01       35 阅读