-
Notifications
You must be signed in to change notification settings - Fork 0
/
148.sort-list.cpp
106 lines (102 loc) · 2.25 KB
/
148.sort-list.cpp
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
/*
* @lc app=leetcode id=148 lang=cpp
*
* [148] Sort List
*
* https://leetcode.com/problems/sort-list/description/
*
* algorithms
* Medium (45.67%)
* Likes: 3943
* Dislikes: 169
* Total Accepted: 341.4K
* Total Submissions: 736K
* Testcase Example: '[4,2,1,3]'
*
* 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: []
*
*
*
* Constraints:
*
*
* The number of nodes in the list is in the range [0, 5 * 10^4].
* -10^5 <= Node.val <= 10^5
*
*
*/
// @lc code=start
/**
* 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* mid = getMid(head);
ListNode* left = sortList(head);
ListNode* right = sortList(mid);
return combine(left, right);
}
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;
}
ListNode* combine(ListNode* left, ListNode* right) {
ListNode dummyHead(0);
ListNode* ptr = &dummyHead;
while (left && right) {
if (left->val < right->val) {
ptr->next = left;
left = left->next;
} else {
ptr->next = right;
right = right->next;
}
ptr = ptr->next;
}
if (left) ptr->next = left;
else ptr->next = right;
return dummyHead.next;
}
};
// @lc code=end