解法一:
快速排序
class Solution {
public:
ListNode* sortList(ListNode* head) {
if(!head || !head->next) return head;
ListNode* cur = head->next;
ListNode* small = new ListNode(0);
ListNode* large = new ListNode(0);
ListNode* sp = small;
ListNode* lp = large;
while(cur){
if(cur->val<head->val){
sp->next = cur;
sp = cur;
}
else{
lp->next = cur;
lp = cur;
}
cur = cur->next;
}
sp->next = NULL;
lp->next = NULL;
small=sortList(small->next);
large=sortList(large->next);
cur = small;
if(cur){
while(cur->next) cur = cur->next;
cur->next = head;
head->next = large;
return small;
}else{
head->next = large;
return head;
}
}
};
解法二:
归并排序
class Solution {
public:
ListNode* merge(ListNode* p1, ListNode* p2){
ListNode* res = new ListNode(0);
ListNode* cur = res;
while(p1 && p2){
if(p1->val<p2->val){
cur->next = p1;
p1 =p1->next;
}else{
cur->next = p2;
p2 = p2->next;
}
cur = cur->next;
}
if (p1) cur->next = p1;
if (p2) cur->next = p2;
return res->next;
}
ListNode* sortList(ListNode* head) {
if(!head || !head->next) return head;
ListNode* fast = head;
ListNode* slow = head;
ListNode* pre = head;
while(fast && fast->next){
pre = slow;
fast = fast->next->next;
slow = slow->next;
}
pre->next = NULL;
return merge(sortList(head), sortList(slow));
}
};