148. Sort List
Description
Given the head
of a linked list, return the list after sorting it in ascending order .
Example 1:
1 2
| Input: head = [4,2,1,3] Output: [1,2,3,4]
|
Example 2:
1 2
| Input: head = [-1,5,3,4,0] Output: [-1,0,3,4,5]
|
Example 3:
1 2
| Input: head = [] Output: []
|
Constraints:
- The number of nodes in the list is in the range
[0, 5 * 10^4]
.
-10^5 <= Node.val <= 10^5
Follow up: Can you sort the linked list in O(n logn)
time and O(1)
memory (i.e. constant space)?
Hints/Notes
Solution
Language: C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
|
class Solution { public: ListNode* sortList(ListNode* head) { if (!head || !head->next) return head; ListNode* mid = getMid(head); ListNode* left = sortList(head); ListNode* right = sortList(mid); return merge(left, right); }
ListNode* merge(ListNode* list1, ListNode* list2) { ListNode dummy(0); ListNode* head = &dummy; while (list1 && list2) { if (list1->val < list2->val) { head->next = list1; list1 = list1->next; } else { head->next = list2; list2 = list2->next; } head = head->next; } if (list1) { head->next = list1; } else { head->next = list2; } return dummy.next; }
ListNode* getMid(ListNode* head) { ListNode* midPrev = nullptr; while (head && head->next) { midPrev = (midPrev == nullptr) ? head : midPrev->next; head = head->next->next; } ListNode* mid = midPrev->next; midPrev->next = nullptr; return mid; } };
|