1+ /*
2+ Given the head of a linked list, return the list after sorting it in ascending order.
3+
4+ Input: head = [4,2,1,3]
5+ Output: [1,2,3,4]
6+
7+ Input: head = [-1,5,3,4,0]
8+ Output: [-1,0,3,4,5]
9+
10+ Input: head = []
11+ Output: []
12+
13+
14+ Constraints:
15+
16+ The number of nodes in the list is in the range [0, 5 * 104].
17+ -105 <= Node.val <= 105
18+
19+ Follow up: Can you sort the linked list in O(n logn) time and O(1) memory (i.e. constant space)?
20+ */
21+
22+ /* *
23+ * Definition for singly-linked list.
24+ * struct ListNode {
25+ * int val;
26+ * ListNode *next;
27+ * ListNode() : val(0), next(nullptr) {}
28+ * ListNode(int x) : val(x), next(nullptr) {}
29+ * ListNode(int x, ListNode *next) : val(x), next(next) {}
30+ * };
31+ */
32+ class Solution {
33+ public:
34+ ListNode* compute_midpoint (ListNode* head){
35+ if (head == NULL || head->next == NULL ){
36+ return head;
37+ }
38+ ListNode* slow = head;
39+ ListNode* fast = head->next ;
40+ while (fast != NULL && fast->next != NULL ){
41+ slow = slow->next ;
42+ fast = fast->next ->next ;
43+ }
44+ return slow;
45+ }
46+ ListNode* merge_two_lists (ListNode* A, ListNode* B){
47+ if (A == NULL )
48+ return B;
49+ else if (B == NULL )
50+ return A;
51+ ListNode* C = NULL ;
52+ if (A->val < B->val ){
53+ C = A;
54+ C->next = merge_two_lists (A->next , B);
55+ }
56+ else {
57+ C = B;
58+ C->next = merge_two_lists (A, B->next );
59+ }
60+ return C;
61+ }
62+ ListNode* sortList (ListNode* head) {
63+ if (head == NULL || head->next == NULL )
64+ return head;
65+ ListNode* mid = compute_midpoint (head);
66+ ListNode* A = head;
67+ ListNode* B = mid->next ;
68+ mid->next = NULL ;
69+ A = sortList (A);
70+ B = sortList (B);
71+
72+ ListNode* C = merge_two_lists (A, B);
73+ return C;
74+ }
75+ };
0 commit comments