[Leetcode] #148 Sort List

来源:互联网 发布:淘宝图书商城 编辑:程序博客网 时间:2024/06/18 14:54

Discription:

Sort a linked list in O(n log n) time using constant space complexity.

Solution:

ListNode* merge(ListNode* left, ListNode* right){if (left == NULL) return right;if (right == NULL) return left;ListNode *result = NULL;if (left->val < right->val){result = left;left = left->next;}else{result = right;right = right->next;}ListNode *curr = result;while (left && right){if (left->val < right->val){curr->next = left;left = left->next;}else{curr->next = right;right = right->next;}curr = curr->next;}curr->next = left ? left : right;return result;}ListNode* sortList(ListNode* head) {if (head == NULL || head->next == NULL) return head;ListNode *pslow = head;ListNode *pfast = head;while (pfast->next && pfast->next->next){pslow = pslow->next;pfast = pfast->next->next;}ListNode *rhalf = pslow->next;pslow->next = NULL;return merge(sortList(head), sortList(rhalf));}

//二刷ListNode *merge(ListNode *head1,ListNode *head2){ListNode *result = new ListNode(-1),*cur = result;while (head1 && head2){if (head1->val < head2->val){cur->next = head1;head1 = head1->next;}else{cur->next = head2;head2 = head2->next;}cur = cur->next;}cur->next = head1 ? head1 : head2;return result->next;}ListNode* sortList(ListNode* head) {if (!head || !head->next)return head;ListNode *pslow = head, *pfast = head->next;while (pfast && pfast->next){pfast = pfast->next->next;pslow = pslow->next;}ListNode *head2 = pslow->next;pslow->next = NULL;return merge(sortList(head), sortList(head2));}

附:Leetcode源代码见我的GitHub  

0 0
原创粉丝点击