Skip to content

Commit 416f9de

Browse files
committed
Update and rename sortList.cpp to sort-list.cpp
1 parent 48cfb2e commit 416f9de

File tree

2 files changed

+52
-59
lines changed

2 files changed

+52
-59
lines changed

C++/sort-list.cpp

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
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+
};

C++/sortList.cpp

Lines changed: 0 additions & 59 deletions
This file was deleted.

0 commit comments

Comments
 (0)