LeetCode Sort List(链表排序)

题目大意:


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

对给定的链表进行排序, 要求时间复杂度是O(n logn) 空间复杂度为O(1), 这道题显然要用归并排序。


c++代码:

class Solution{

public:
    ListNode* SortList(ListNode* head)
    {
        if(head == NULL || head->next == NULL)
        {
            return head;
        }
        ListNode* fast = head;
        ListNode* slow = head;
        while (fast->next != NULL) {
            
            fast = fast->next->next;
            if(fast == NULL)
                break;
            slow = slow->next;
        }
        ListNode* right = slow->next;
        slow->next = NULL;
        //recursive to sort left and right list
        ListNode* left = SortList(head);
        right = SortList(right);
        //merge two sorted list
        return MergeTwoList(left, right);
    }
    
    ListNode* MergeTwoList(ListNode* l1, ListNode* l2)
    {
        if(NULL == l1)
            return l2;
        if(NULL == l2)
            return l1;
        ListNode* node = NULL;
        if(l1->val <= l2->val)
        {
            node = l1;
            l1 = l1->next;
        }
        else
        {
            node = l2;
            l2 = l2->next;
        }
        ListNode* head = node;
        while(l1 != NULL && l2 != NULL)
        {
            if(l1->val <= l2->val)
            {
                node->next = l1;
                l1 = l1->next;
                node = node->next;
            }
            else
            {
                node->next = l2;
                l2 = l2->next;
                node = node->next;
            }
            
        }
        if(l1 != NULL)
            node->next = l1;
        else if(l2 != NULL)
            node->next = l2;
        return head;
    }
    
};


你可能感兴趣的:(LeetCode,C++,面试,链表)