首页 > 代码库 > Sort List -- LeetCode
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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。