/**
* 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){
return head;
}
if(head->next == NULL){
return head;
}
if(head->next->next == NULL){
if(head->next->val < head->val){
ListNode *tmp = head->next;
head->next->next = head;
head->next = NULL;
return tmp;
}
else{
return head;
}
}
ListNode* fast, *slow;
fast = slow = head;
while(fast->next){
fast = fast->next->next;
slow = slow->next;
if(fast == NULL){
break;
}
}
ListNode* rec = slow, *recnext = slow->next;
ListNode *first, *second;
slow->next = NULL;
first = sortList(head);
second = sortList(recnext);
ListNode *newhead = new ListNode(0);
ListNode *newtmp = newhead;
while(first != NULL && second != NULL){
if(first->val <= second->val){
newtmp->val = first->val;
first = first->next;
}
else{
newtmp->val = second->val;
second = second->next;
}
newtmp->next = new ListNode(0);
newtmp = newtmp->next;
}
if(first != NULL){
newtmp->val = first->val;
newtmp->next = first->next;
}
else{
newtmp->val = second->val;
newtmp->next = second->next;
}
return newhead;
}
};
leetcode Sort List
最新推荐文章于 2022-02-24 15:47:33 发布