1 题目
Sort a linked list in O(n log n) time using constant space complexity.
Example 1:
Input: 4->2->1->3
Output: 1->2->3->4
Example 2:
Input: -1->5->3->4->0
Output: -1->0->3->4->5
2 标准解
class Solution {
public:
ListNode* sortList(ListNode* head) {
if(head == NULL) return head;
ListNode* pre = new ListNode(0);
pre->next =head;
ListNode* cur = head;
while(cur->next!=NULL){
ListNode*traverse = pre;
while(cur->next->val > traverse->next->val && cur->next != traverse->next)
traverse = traverse->next;
if(traverse == cur){
cur = cur->next;
continue;
}
else{
ListNode* temp = cur->next->next;
cur->next->next = traverse->next;
traverse->next =cur->next;
cur->next = temp;
}
}
return pre->next;
}
};