博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode:Sort List
阅读量:4346 次
发布时间:2019-06-07

本文共 2118 字,大约阅读时间需要 7 分钟。

题目如下:()

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

在中使用了插入排序,时间复杂度为O(n^2)。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         // IMPORTANT: Please reset any member data you declared, as13         // the same Solution instance will be reused for each test case.14         //链表归并排序15         if(head == NULL || head->next == NULL)return head;16         else17         {18             //快慢指针找到中间节点19             ListNode *fast = head,*slow = head;20             while(fast->next != NULL && fast->next->next != NULL)21             {22                 fast = fast->next->next;23                 slow = slow->next;24             }25             fast = slow;26             slow = slow->next;27             fast->next = NULL;28             fast = sortList(head);//前半段排序29             slow = sortList(slow);//后半段排序30             return merge(fast,slow);31         }32         33     }34     // merge two sorted list to one35     ListNode *merge(ListNode *head1, ListNode *head2)36     {37         if(head1 == NULL)return head2;38         if(head2 == NULL)return head1;39         ListNode *res , *p ;40         if(head1->val < head2->val)41             {res = head1; head1 = head1->next;}42         else{res = head2; head2 = head2->next;}43         p = res;44         45         while(head1 != NULL && head2 != NULL)46         {47             if(head1->val < head2->val)48             {49                 p->next = head1;50                 head1 = head1->next;51             }52             else53             {54                 p->next = head2;55                 head2 = head2->next;56             }57             p = p->next;58         }59         if(head1 != NULL)p->next = head1;60         else if(head2 != NULL)p->next = head2;61         return res;62     }63 };

【版权声明】转载请注明出处:

转载于:https://www.cnblogs.com/TenosDoIt/p/3434550.html

你可能感兴趣的文章
Android -- ListView与Adapter
查看>>
《House of Cards》观后感
查看>>
1005 Spell It Right (20 分)
查看>>
编辑完这一条数据如何继续转入下一条数据(快速编辑)
查看>>
mysql编译安装
查看>>
[转]Python中的getattr()函数详解
查看>>
execvp php-fpm reload使用的函数
查看>>
SpringBoot系列: 使用 Swagger 生成 API 文档
查看>>
Quadro P5200 - 最强大的移动工作站显卡 专门为了惠普 VR Z 背包电脑而发布
查看>>
离散事件模拟-银行管理
查看>>
学习笔记5
查看>>
Linux的五个查找命令
查看>>
【Dataset】Goodbooks-10k: 图书推荐数据
查看>>
怎样更改VS2010帮助文档的位置
查看>>
JS中的call()和apply()方法
查看>>
mac Zip 常用命令
查看>>
PHP的学习--cookie和session--来自copy_02
查看>>
异界冒险隐私协议
查看>>
一个简单的C语言语法检查器的实现
查看>>
Unity3D学习笔记(二十五):Json
查看>>