菜单 学习猿地 - LMONKEY

VIP

开通学习猿地VIP

尊享10项VIP特权 持续新增

知识通关挑战

打卡带练!告别无效练习

接私单赚外块

VIP优先接,累计金额超百万

学习猿地私房课免费学

大厂实战课仅对VIP开放

你的一对一导师

每月可免费咨询大牛30次

领取更多软件工程师实用特权

入驻
420
0

Sort List

原创
05/13 14:22
阅读数 22109

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

思路:

归并排序。题目要求固定空间,不知道这种递归实现的算不算固定空间。

代码:

 1     ListNode *sortList(ListNode *head, int length){
 2         if(length <= 1)
 3             return head;
 4         int l = length/2;
 5         ListNode *tmp = head;
 6         int num = 0;
 7         ListNode *half = NULL;
 8         while(tmp){
 9             num++;
10             if(num == l){
11                 break;
12             }
13             tmp = tmp->next;
14         }
15         half = tmp->next;
16         tmp->next = NULL;
17         ListNode *first = sortList(head, l), *second = sortList(half, length-l);
18         ListNode *result = NULL, *newhead;
19         while(first&&second){
20             if(first->val < second->val){
21                 if(result){
22                     result->next = first;
23                     result = result->next;
24                 }
25                 else{
26                     result = first;
27                     newhead = result;
28                 }
29                 first = first->next;
30             }
31             else{
32                 if(result){
33                     result->next = second;
34                     result = result->next;
35                 }
36                 else{
37                     result = second;
38                     newhead = result;
39                 }
40                 second = second->next;
41             }
42         }
43         if(first)
44             result->next = first;
45         if(second)
46             result->next = second;
47         return newhead;
48     }
49     ListNode *sortList(ListNode *head) {
50         // IMPORTANT: Please reset any member data you declared, as
51         // the same Solution instance will be reused for each test case.
52         if(head == NULL || head->next == NULL)
53             return head;
54         int length = 0;
55         ListNode *tmp = head;
56         while(head){
57             length++;
58             head = head->next;
59         }
60         return sortList(tmp, length);
61     }

 第一遍归并排序是从中间分开的,还可以把链表按单双节点分别构成新链表。

发表评论

0/200
420 点赞
0 评论
收藏