LeetCode 148. Sort List
1 class Solution { 2 public: 3 ListNode* getMid(ListNode* head){ 4 ListNode* slow = head, * fast = head; 5 while(fast->next && fast->next->next){ 6 slow = slow->next; 7 fast = fast->next->next; 8 } 9 return slow; 10 } 11 ListNode* merge(ListNode* head){ 12 if(head->next == NULL) return head; 13 ListNode* mid = getMid(head); 14 ListNode* head2 = mid->next; 15 mid->next = NULL; 16 ListNode* new_head1 = merge(head); 17 ListNode* new_head2 = merge(head2); 18 19 ListNode* res = new ListNode(0); 20 ListNode* resH = res; 21 while(new_head1 && new_head2){ 22 if(new_head1->val < new_head2->val){ 23 res->next = new_head1; 24 res = res->next; 25 new_head1 = new_head1->next; 26 } 27 else{ 28 res->next = new_head2; 29 res = res->next; 30 new_head2 = new_head2->next; 31 } 32 } 33 while(new_head1){ 34 res->next = new_head1; 35 res = res->next; 36 new_head1 = new_head1->next; 37 } 38 while(new_head2){ 39 res->next = new_head2; 40 res = res->next; 41 new_head2 = new_head2->next; 42 } 43 return resH->next; 44 } 45 ListNode* sortList(ListNode* head) { 46 if(head == NULL) return head; 47 return merge(head); 48 } 49 };
merge思想,应该还有更快算法,留坑。