题解 | #单链表的排序#

单链表的排序

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));
}

全部评论

相关推荐

点赞 评论 收藏
分享
零OFFER战士:另一个版本查看图片
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
06-11 13:34
offe从四面八方来:我真的没时间陪你闹了
点赞 评论 收藏
分享
难怪不开摄像头,全是简单的性格题,比大疆友善多了
NULL10086:今早上发的测评,我这还没做呢,官网上已经显示挂了
投递大疆等公司7个岗位
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务