# Leetcode：148_Sort List | O(nlogn)链表排序 | Medium

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

 1 ListNode *sortList(ListNode *head)
2 {
5         return NULL;
6
8     int len = 0;        //get the length of link
9     while (NULL != p) {
10         p = p->next;
11         len ++;
12     }
13
14     ListNode *temp = new ListNode(0);
16
17     int interval = 1;   //合并子列表的长度
18     for (; interval <= len; interval *= 2) {
19         ListNode *pre = temp;
20         ListNode *first = temp->next;  //两段子列表的起始位置
21         ListNode *second = temp->next;
22
23         while (NULL != first || NULL != second) {
24             int i = 0;
25             while (i < interval && NULL != second) {
26                 second = second->next; //将second移到第二段子列表的起始处
27                 i ++;
28             }
29
30             int fvisit = 0, svisit = 0; //访问子列表的的次数<interval，保证列表中的元素全部能被访问
31             while (fvisit < interval && svisit < interval && NULL != first && NULL != second) {
32                 if (first->val < second->val) {
33                     pre->next = first;
34                     pre = first;
35                     first = first->next;
36                     fvisit ++;
37                 }
38                 else {
39                     pre->next = second;
40                     pre = second;
41                     second = second->next;
42                     svisit ++;
43                 }
44             }
45             while (fvisit < interval && NULL != first) {
46                 pre->next = first;
47                 pre = first;
48                 first = first->next;
49                 fvisit ++;
50             }
51             while (svisit < interval && NULL != second) {
52                 pre->next = second;
53                 pre = second;
54                 second = second->next;
55                 svisit ++;
56             }
57             pre->next = second;
58             first = second;
59         }
60     }
61     ListNode *retResult = temp->next;
62     delete temp;
63     temp = NULL;
64     return retResult;
65 }

posted @ 2014-10-07 17:06  猿大白  阅读(3278)  评论(0编辑  收藏