148. Sort List
Given the head of a linked list, return the list after sorting it in ascending order.
Follow up: Can you sort the linked list in O(n logn) time and O(1) memory (i.e. constant space)?
Example 1:
Input: head = [4,2,1,3]
Output: [1,2,3,4]
Example 2:
Input: head = [-1,5,3,4,0]
Output: [-1,0,3,4,5]
Example 3:
Input: head = []
Output: []
Solution
C++
/**
* 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* sortList(ListNode* head) {
if(!head || !head->next) return head;
ListNode* slow = head,* fast = head->next;
while(fast && fast->next) {
fast = fast->next->next;
slow = slow->next;
}
fast = slow->next;
slow->next = NULL;
return merge(sortList(head),sortList(fast));
}
ListNode* merge(ListNode* l, ListNode* r) {
ListNode* head = new ListNode(0);
ListNode* dummy = head;
while(l && r) {
if(l->val < r->val) {
dummy->next = l;
l = l->next;
}
else {
dummy->next = r;
r = r->next;
}
dummy = dummy->next;
}
dummy->next = l ? l : r;
return head->next;
}
};
Explanation
merge sort: