排序例题

1.sort list
思路:
通过将链表进行分区,然后递归分区合并链表。
重点在于链表的分区过程。
代码如下

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
class Solution {
public:

ListNode* sortList(ListNode* head) {
if (head==NULL ||head->next==NULL) return head;
ListNode *fast=head,*slow=head;
while(fast->next!=NULL && fast->next->next!=NULL){
fast = fast->next->next;
slow = slow->next;
}
fast = slow->next;
slow->next = NULL;
return merge(sortList(head),sortList(fast));
}
ListNode* merge(ListNode* l1,ListNode*l2){
if(!l1){return l2;}
if(!l2){return l1;}
ListNode*head,*cur;
if(l1->val>l2->val){
head = l2;l2 = l2->next;cur = head;
}else{
head = l1;l1 = l1->next;cur = head;
}
while(l1&&l2){
if(l1->val>l2->val){
cur->next = l2;
l2 = l2->next;
}else{
cur->next = l1;
l1 = l1->next;
}
cur = cur->next;
}
if(l1){
cur->next = l1;
}
if(l2){
cur->next = l2;
};
return head;
}
};