【力扣hot100题】(032)排序链表

【力扣hot100题】(032)排序链表_第1张图片

挺难的,主要是对排序算法不熟悉。

看了答案,归并排序真的是一个很好的解法。

大致思路是递归,将链表不断拆分为小块,每块进行排序后合并新块。

这种排序对链表来说真的是个很不错的选择,因为链表二分可以用快慢指针,合并之前做过,很好做。

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* dg(ListNode* head,ListNode* tail){
        if(head==nullptr) return head;
        if(head->next==tail){
            head->next=nullptr;
            return head;
        }
        ListNode* slow=head;
        ListNode* fast=head;
        while(fast!=tail){
            slow=slow->next;
            fast=fast->next;
            if(fast!=tail) fast=fast->next;
        }
        ListNode* h=dg(head,slow);
        ListNode* t=dg(slow,tail);
        ListNode* pre=new ListNode(0);
        ListNode* result=pre;
        while(h||t){
            if(t==nullptr||h&&h->valval){
                pre->next=h;
                h=h->next;
            }
            else if(h==nullptr||h->val>=t->val){
                pre->next=t;
                t=t->next;
            }
            pre=pre->next;
        }
        return result->next;
    }
    ListNode* sortList(ListNode* head) {
        return dg(head,nullptr);
    }
};

你可能感兴趣的:(leetcode,链表,算法)