【leetcode】Sort List

Sort List
Sort a linked list in O(n log n) time using constant space complexity.
 
 
需要采用归并排序对链表进行操作。
 
归并排序思想:每次选取链表中间元素,把链表分割成两部分,
递归分割,直到链表中的元素是有序的时候(即只有一个元素时候),这时对链表进行合并,
合并的时候,每次选两个链表中小的元素放在下一个位置。
 
 
 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 
12     ListNode *mergeList(ListNode *h1,ListNode *h2)
13     {
14        ListNode *head=new ListNode(0);
15        ListNode *cur=head;
16        while(h1!=NULL&&h2!=NULL)
17        {
18            if(h1->val>h2->val)
19            {
20                cur->next=h2;
21                h2=h2->next;
22            }
23            else
24            {
25                cur->next=h1;
26                h1=h1->next;
27            }
28            
29            cur=cur->next;
30        }
31        
32        cur->next=h1==NULL?h2:h1;
33        
34        cur=head;
35        head=head->next;
36        delete cur;
37        
38        return head;
39     }
40     
41 
42     
43     ListNode *sortList(ListNode *head) {
44         
45         
46         if(head==NULL||head->next==NULL) return head;
47         
48         ListNode *slow,*fast;
49         slow=fast=head;
50         while(fast->next!=NULL&&fast->next->next!=NULL)
51         {
52             fast=fast->next->next;
53             slow=slow->next;
54         }
55         
56         ListNode *mid=slow->next;
57         slow->next=NULL;
58         
59         ListNode *h1=sortList(head);
60         ListNode *h2=sortList(mid);
61         return mergeList(h1,h2);
62         
63         
64     }
65 };

 

posted @ 2014-12-24 21:24  H5开发技术  阅读(145)  评论(0编辑  收藏  举报