Sort List -- LeetCode
Posted Coder and Writer
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Sort List -- LeetCode相关的知识,希望对你有一定的参考价值。
Sort a linked list in O(n log n) time using constant space complexity.
思路:模拟merge sort。
1 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * ListNode *next; 6 * ListNode(int x) : val(x), next(NULL) {} 7 * }; 8 */ 9 class Solution { 10 public: 11 ListNode* sortList(ListNode* head) { 12 if (head == NULL || head->next == NULL) return head; 13 ListNode *slow = head, *fast = head; 14 while (fast->next && fast->next->next) { 15 fast = fast->next->next; 16 slow = slow->next; 17 } 18 ListNode *head2 = slow->next; 19 slow->next = NULL; 20 head = sortList(head); 21 head2 = sortList(head2); 22 return merge(head, head2); 23 } 24 ListNode* merge(ListNode* left, ListNode* right) { 25 if (left == NULL) return right; 26 else if (right == NULL) return left; 27 if (left->val < right->val) { 28 left->next = merge(left->next, right); 29 return left; 30 } 31 right->next = merge(left, right->next); 32 return right; 33 } 34 };
以上是关于Sort List -- LeetCode的主要内容,如果未能解决你的问题,请参考以下文章
Leetcode147. Insertion Sort List
LeetCode 147. Insertion Sort List