题解 | #单链表的排序#

单链表的排序

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

/**
 * struct ListNode {
 *  int val;
 *  struct ListNode *next;
 *  ListNode(int x) : val(x), next(nullptr) {}
 * };
 */

/*
class Solution {
public:
   ListNode* sortInList(ListNode* head) {
       // write code here
       vector<int> vec;
       ListNode* p=head;
       while(p) {
           vec.push_back(p->val);
           p=p->next;
       }
       sort(vec.begin(),vec.end());
       ListNode* dummy= new ListNode(0);
       p = dummy;
       for(int i=0;i<vec.size();i++) {
           ListNode* tmpNode = new ListNode(vec[i]);
           p->next=tmpNode;
           p=p->next;
       }
       p=nullptr;
       return dummy->next;
   }
};
*/
class Solution {
  public:
    ListNode* sortInList(ListNode* head) {
        if (head == nullptr || head->next == nullptr)
            return head;
        ListNode* slow = head;
        ListNode* fast = head;
        // 使用快慢指针寻找链表的中点
        while(fast && fast->next && fast->next->next) {
            slow = slow->next;
            fast = fast->next->next;
        }

        ListNode* tmp = slow->next;
        slow->next = nullptr;
        // 递归左右两边进行排序
        ListNode* left = sortInList(head);
        ListNode* right = sortInList(tmp);
        // 创建新的链表
        ListNode* dummy = new ListNode(0);
        ListNode* h = dummy;
        // 合并 left right两个链表
        while (left && right) {
            if (left->val <= right->val) {
                h->next = left;
                left = left->next;
            } else {
                h->next = right;
                right = right->next;
            }
            h = h->next;
        }
        // 最后添加未对比的链表部分判断左链表是否为空
        h->next = left != nullptr ? left : right;
        return dummy->next;
    }
};

全部评论

相关推荐

01-16 18:34
四川大学 Java
欢迎加入AI:没有啥稳定不稳定,一切都源于业务快速发展还是收缩。我当年一开始去的央企,业务不赚钱,也贼卷,慢慢就开始优化了。。。
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务