首页 > 其他 > 详细

Sort List -- LeetCode

时间:2016-09-01 12:26:34      阅读:186      评论:0      收藏:0      [点我收藏+]

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

原文:http://www.cnblogs.com/fenshen371/p/5829027.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!