题解 | #单链表的排序#

单链表的排序

https://www.nowcoder.com/practice/f23604257af94d939848729b1a5cda08

struct ListNode* Merge(struct ListNode* pHead1, struct ListNode* pHead2 ) {
    struct ListNode* yhead = (struct ListNode*)malloc(sizeof(struct ListNode));
    struct ListNode* cur = yhead;

    while (pHead1 && pHead2) {
        if (pHead1->val <= pHead2->val) {
            cur->next = pHead1;
            pHead1 = pHead1->next;
        } else {
            cur->next = pHead2;
            pHead2 = pHead2->next;
        }
        cur = cur->next;
    }
    cur->next = pHead1 ? pHead1 : pHead2;
    return yhead->next;
}

struct ListNode* sortInList(struct ListNode* head ) {
    if (!head || !head->next)  return head;
    struct ListNode* left = head;
    struct ListNode* mid = head->next;
    struct ListNode* right = head->next->next;

    while (right && right->next) {
        left = left->next;
        mid = mid->next;
        right = right->next->next;
    }
    left->next = NULL;
    return Merge(sortInList(head), sortInList(mid));
}

全部评论

相关推荐

孤寡孤寡的牛牛很热情:为什么我2本9硕投了很多,都是简历或者挂,难道那个恶心人的测评真的得认真做吗
点赞 评论 收藏
分享
比亚迪汽车新技术研究院 硬件工程师 总包21左右 硕士
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务