码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode-Sort List

时间:2014-10-26 10:17:34      阅读:186      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   io   ar   for   sp   div   

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

链表排序。要达到nlogn的时间复杂度,能想到归并排序与快速排序。

这里采用归并排序:

 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 || !head->next)
13             return head;
14         mergeSort(head);
15     }
16     
17     ListNode *mergeSort(ListNode *head) {
18         if(!head || !head->next)
19             return head;
20         //fast-slow
21         ListNode *p = head, *q = head, *pre = NULL;
22         while(q && q->next!=NULL)
23         {
24             pre = p;
25             p = p->next;
26             q = q->next->next;
27         }
28         pre->next = NULL;
29         ListNode *left = mergeSort(head);
30         ListNode *right = mergeSort(p);
31         
32         return merge(left,right);
33     }
34     
35     ListNode *merge(ListNode *left, ListNode *right){
36         ListNode *p = new ListNode(0);
37         ListNode *temp = p ;
38         while(left && right){
39             if(left->val <= right->val){
40                 temp->next = left;
41                 left = left->next;
42             }else{
43                 temp->next = right;
44                 right = right->next;
45             }
46             temp=temp->next;
47         }
48         if(left)
49             temp->next = left;
50         else
51             temp->next = right;
52         
53         temp = p->next;
54         p->next = NULL;
55         delete p;
56         return temp;
57     }
58 };

 

转自:http://blog.csdn.net/jiadebin890724/article/details/21334059

LeetCode-Sort List

标签:style   blog   http   color   io   ar   for   sp   div   

原文地址:http://www.cnblogs.com/crazelee/p/4051425.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!