Skip to content

Commit 34f8a28

Browse files
committed
Create Sort_List.cc
1 parent df04ab5 commit 34f8a28

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

Sort_List.cc

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

0 commit comments

Comments
 (0)