File tree 2 files changed +52
-59
lines changed 2 files changed +52
-59
lines changed Original file line number Diff line number Diff line change
1
+ // Time: O(nlogn)
2
+ // Space: O(logn)
3
+
4
+ /* *
5
+ * Definition for singly-linked list.
6
+ * struct ListNode {
7
+ * int val;
8
+ * ListNode *next;
9
+ * ListNode(int x) : val(x), next(NULL) {}
10
+ * };
11
+ */
12
+ class Solution {
13
+ public:
14
+ ListNode* sortList (ListNode* head) {
15
+ if (!head || !head->next ) {
16
+ return head;
17
+ }
18
+
19
+ auto slow = head, fast = head;
20
+ while (fast->next && fast->next ->next ) {
21
+ slow = slow->next ;
22
+ fast = fast->next ->next ;
23
+ }
24
+
25
+ // Split linked list.
26
+ fast = slow;
27
+ slow = slow->next ;
28
+ fast->next = nullptr ;
29
+
30
+ return mergeTwoLists (sortList (head), sortList (slow));
31
+ }
32
+
33
+ private:
34
+ ListNode *mergeTwoLists (ListNode *l1, ListNode *l2) {
35
+ ListNode dummy = ListNode{0 };
36
+ auto *curr = &dummy;
37
+
38
+ while (l1 && l2) {
39
+ if (l1->val <= l2->val ) {
40
+ curr->next = l1;
41
+ l1 = l1->next ;
42
+ } else {
43
+ curr->next = l2;
44
+ l2 = l2->next ;
45
+ }
46
+ curr = curr->next ;
47
+ }
48
+ curr->next = l1 ? l1 : l2;
49
+
50
+ return dummy.next ;
51
+ }
52
+ };
Load Diff This file was deleted.
You can’t perform that action at this time.
0 commit comments