做题思路:先使用快慢指针确定链表的中间位置(注意慢指针的位置)。再对两个链表递归调用排序,最后再合并两个已排好序的单链表。
/**
* 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==NULL || head->next==NULL)
return head;
ListNode *slow=head,*fast = head;
while(fast && fast->next){
fast = fast->next->next;
if(fast)
slow = slow->next;
}
ListNode *pa = head;
ListNode *pb = slow->next;
slow->next = NULL;
pa = sortList(pa);
pb = sortList(pb);
ListNode *cur = NULL;
if(pa->val < pb->val){
cur = pa;
ListNode *tmp = cur->next;
cur->next = NULL;
pa = tmp;
head = cur;
}else{
cur = pb;
ListNode *tmp = cur->next;
cur->next = NULL;
pb = tmp;
head = cur;
}
while(pa && pb){
if(pa->val <pb->val){
cur->next = pa;
pa = pa->next;
cur = cur->next;
cur->next = NULL;
}
else{
cur->next = pb;
pb = pb->next;
cur = cur->next;
cur->next = NULL;
}
}
if(pa)
cur->next = pa;
if(pb)
cur->next = pb;
return head;
}
};