题解 | #单链表的排序#

单链表的排序

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

/**
 * struct ListNode {
 *	int val;
 *	struct ListNode *next;
 *	ListNode(int x) : val(x), next(nullptr) {}
 * };
 */
#include <climits>
class Solution {
public:
    ListNode *mergeList(ListNode *head1, ListNode *head2){
        ListNode tmp(0);
        ListNode *newHead = &tmp, *curH1 = head1, *curH2 = head2;
        while (curH1 && curH2) {
            if (curH1->val < curH2->val) {
                newHead->next = curH1;
                curH1 = curH1->next;
            } else {
                newHead->next = curH2;
                curH2 = curH2->next;
            }
            newHead = newHead->next;
        }
        if (curH1) {
            newHead->next = curH1;
        }
        if (curH2) {
            newHead->next = curH2;
        }
        return tmp.next;
    }
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param head ListNode类 the head node
     * @return ListNode类
     */
    ListNode* sortInList(ListNode* head) {
        if (head == nullptr || head->next == nullptr) {
            return head;
        }
        ListNode *slow = head, *fast = slow->next;
        //查找链表中点
        while (fast && fast->next) {
            slow = slow->next;
            fast = fast->next->next;
        }
        ListNode *tmp = slow->next;
        slow->next = nullptr;
        ListNode *head1 = sortInList(head);
        ListNode *head2 = sortInList(tmp);
        ListNode *newHead = mergeList(head1, head2);
        return newHead;
    }
};

全部评论

相关推荐

object3:开始给部分🌸孝子上人生第一课了
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务