题解 | #单链表的排序#

单链表的排序

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

/**
 * struct ListNode {
 *	int val;
 *	struct ListNode *next;
 *	ListNode(int x) : val(x), next(nullptr) {}
 * };
 */
class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param head ListNode类 the head node
     * @return ListNode类
     */
    ListNode* sortInList(ListNode* head) {
        // write code here
        if (!head || !head->next) {
            return head;
        }
        ListNode* fast = head;
        ListNode* slow = head;
        ListNode* pre_slow = nullptr;
        while (fast && fast->next) {
            fast = fast->next->next;
            pre_slow = slow;
            slow = slow->next;
        }
        
        pre_slow->next = nullptr;
        return merge2List(sortInList(head), sortInList(slow));
    }

private:
    ListNode* merge2List(ListNode* head1, ListNode* head2) {
        if (!head1) {
            return head2;
        }
        if (!head2) {
            return head1;
        }
        ListNode* new_head = new ListNode(-1);
        ListNode* res_head = new_head;
        new_head->next = head1;
        while (head1 && head2) {
            if (head1->val < head2->val) {
                new_head->next = head1;
                head1 = head1->next;
                new_head = new_head->next;
            } else {
                new_head->next = head2;
                head2 = head2->next;
                new_head = new_head->next;
            }
        }
        if (head1) {
            new_head->next = head1;
        }
        if (head2) {
            new_head->next = head2;
        }

        return res_head->next;
    }
};

全部评论

相关推荐

vegetable_vegetable:我也是这个部门这个岗位,但我投的是测开,却被后端捞了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务