用递归实现的归并排序,能通过,但是感觉效果不是很好,
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* sortList(ListNode* head) {
if(!head || !head->next){
return head;
}
ListNode* slow = head, *fast = head, *last = head;
while(fast && fast->next){
last = slow;
slow = slow->next;
fast = fast->next->next;
}
last->next = NULL;//last为前一段的最终
return merge(sortList(head), sortList(slow));
}
ListNode* merge(ListNode* l1, ListNode* l2){
if(!l1) return l2;
if(!l2) return l1;
if(l1->val <= l2->val){
l1->next = merge(l1->next, l2);
return l1;
}else{
l2->next = merge(l1, l2->next);
return l2;
}
return NULL;
// ListNode* n = new ListNode(-1);
// ListNode* cur = n;
// while(l1 && l2){
// if(l1->val <= l2->val){
// cur->next = l1;
// l1 = l1->next;
// }else{
// cur->next = l2;
// l2 = l2->next;
// }
// cur = cur->next;
// }
// if(!l1) cur->next = l2;
// if(!l2) cur->next = l1;
// return n->next;
}
};