题解 | #单链表的排序#

单链表的排序

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

/**
 * struct ListNode {
 *	int val;
 *	struct ListNode *next;
 * };
 */
/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 *
 * 
 * @param head ListNode类 the head node
 * @return ListNode类
 */
struct ListNode* sortInList(struct ListNode* head ) {
    // write code here
    if(head == NULL || head->next == NULL) return head;
    struct ListNode *right = head, *mid = head, *left = head;
    while(right && right->next) {
        right = right->next->next;
        if(right == NULL || right->next == NULL) {
            left = mid;
        }
        mid = mid->next;
    }
    left->next = NULL;
    left = sortInList(head);
    right = sortInList(mid);
    printf("left: %d\nright: %d\n", left->val, right->val);
    struct ListNode dummy;
    struct ListNode* cur = &dummy;
    while(left != NULL && right != NULL) {
        if(left->val <= right->val) {
            cur->next = left;
            left = left->next;
        } else {
            cur->next = right;
            right = right->next;
        }
        cur = cur->next;
    }
    if(left) {
        cur->next = left;
    } else if(right) {
        cur->next = right;
    }
    
    return dummy.next;
}

全部评论

相关推荐

拒绝无效加班的小师弟很中意你:求职意向没有,年龄、课程冗余信息可以删掉,需要提升项目经历。排版需要修改。
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务