148. Sort List

Problem:

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

Example 1:

Input: 4->2->1->3
Output: 1->2->3->4

Example 2:

Input: -1->5->3->4->0
Output: -1->0->3->4->5

Solutions:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* sortList(ListNode* head) {
        if (head == nullptr)    return nullptr;
        if (head->next == nullptr)  return head;

        ListNode* slow = head;
        ListNode* fast = head;

        while (fast->next !=  nullptr && fast->next->next != nullptr) {
            slow = slow->next;
            fast = fast->next->next;
        }

        ListNode* head2 = slow->next;
        slow->next = nullptr;

        ListNode* leftHead = sortList(head);
        ListNode* rightHead = sortList(head2);

        ListNode* dummy = new ListNode(0);
        ListNode* tail = dummy;

        while (leftHead != nullptr && rightHead != nullptr) {
            if (leftHead->val < rightHead->val) {
                tail->next = leftHead;
                tail = leftHead;
                leftHead = leftHead->next;
            } else {
                tail->next = rightHead;
                tail = rightHead;
                rightHead = rightHead->next;
            }
        }

        if (leftHead == nullptr) {
            tail->next = rightHead;
        } else {
            tail->next = leftHead;
        }

        return dummy->next;
    }
};

results matching ""

    No results matching ""