File tree Expand file tree Collapse file tree 1 file changed +47
-0
lines changed Expand file tree Collapse file tree 1 file changed +47
-0
lines changed Original file line number Diff line number Diff line change
1
+ /* *
2
+ * Definition for singly-linked list.
3
+ * struct ListNode {
4
+ * int val;
5
+ * ListNode *next;
6
+ * ListNode(int x) : val(x), next(NULL) {}
7
+ * };
8
+ */
9
+ class Solution {
10
+ public:
11
+ ListNode *sortList (ListNode *head) {
12
+ // IMPORTANT: Please reset any member data you declared, as
13
+ // the same Solution instance will be reused for each test case.
14
+ if (!head || !head->next )
15
+ return head;
16
+ ListNode *fast = head, *slow = head, *tmp = NULL ;
17
+
18
+ // split
19
+ while (fast && fast->next ) {
20
+ fast = fast->next ->next ;
21
+ tmp = slow;
22
+ slow = slow->next ;
23
+ }
24
+ tmp->next = NULL ;
25
+
26
+ // recursion
27
+ head = sortList (head);
28
+ slow = sortList (slow);
29
+
30
+ // merge
31
+ ListNode *ret = NULL ;
32
+ ListNode **pCur = &ret;
33
+ while (head && slow) {
34
+ if (head->val <= slow->val ) {
35
+ *pCur = head;
36
+ head = head->next ;
37
+ } else {
38
+ *pCur = slow;
39
+ slow = slow->next ;
40
+ }
41
+ pCur = &((*pCur)->next );
42
+ }
43
+ if (head) *pCur = head;
44
+ if (slow) *pCur = slow;
45
+ return ret;
46
+ }
47
+ };
You can’t perform that action at this time.
0 commit comments