首页 > 代码库 > Leetcode:Sort List 对单链表归并排序

Leetcode:Sort List 对单链表归并排序

Sort a linked list in O(n log n) time using constant space complexity.

看到O(n log n)的排序算法,适合单链表的首先想到的就是归并排序

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode * findListMid(ListNode * head)
    {
        if(head == NULL)return NULL;
        ListNode * fast = head;
        ListNode * slow = head;
        while(fast->next)
        {
            if(fast->next->next)
            {
                fast = fast->next->next;
                slow = slow->next;
            }
            else
                return slow;
        }
        return slow;
    }
    ListNode * merge(ListNode * list1,ListNode * list2)
    {
        if(list1 == NULL)return list2;
        if(list2 == NULL)return list1;
        ListNode * head = NULL;
        if(list1->val >= list2->val)
        {
            head = list2;
            list2 = list2->next;
        }
        else
            if(list1->val < list2->val)
            {
                head = list1;
                list1 = list1->next;
            }
            ListNode * tail = head;
        while(list1 && list2)
        {
            if(list1->val >= list2->val)
            {
                tail->next = list2;
                tail = list2;
                list2 = list2->next;
            }  
            else
                if(list1->val < list2->val)
                {
                    tail->next = list1;
                    tail = list1;
                    list1 = list1->next;
                }  
        }
        if(list1)
            tail->next = list1;
        if(list2)
            tail->next = list2;
        return head;
    }
    ListNode *sortList(ListNode *head) {
        if(head == NULL)return NULL;
        if(head->next == NULL)return head;
        ListNode * mid = findListMid(head);
        ListNode * m = mid->next;
        mid->next = NULL;
        ListNode * list1 = sortList(head);
        ListNode * list2 = sortList(m);
        ListNode * list = merge(list1,list2);
        return list;
    }
};