题目:

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

思路:

nlogn的排序有快速排序、归并排序、堆排序。双向链表用快排比较适合,堆排序也可以用于链表,单向链表适合用归并排序。

/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} head
* @return {ListNode}
*/
var sortList = function(head) {
if(head==null||head.next==null){
return head;
}else{
var slow=head,fast=head;
while(fast.next!=null&&fast.next.next!=null){
slow=slow.next;
fast=fast.next.next;
}
//拆成两个链表
fast=slow;
slow=slow.next;
fast.next=null; fast=sortList(head);
slow=sortList(slow);
return merge(fast,slow);
}
}; function merge(head1,head2){
if(head1==null){
return head2;
}
if(head2==null){
return head1;
}
var res=new ListNode(),p=new ListNode();
if(head1.val<head2.val){
res=head1;
head1=head1.next;
}else{
res=head2;
head2=head2.next;
}
p=res; while(head1!=null&&head2!=null){
if(head1.val<head2.val){
p.next=head1;
head1=head1.next;
}else{
p.next=head2;
head2=head2.next;
}
p=p.next;
} if(head1!=null){
p.next=head1;
}else if(head2!=null){
p.next=head2;
} return res;
}

最新文章

  1. Android Stdio 调试Smali
  2. Nexus安装及部署(含如何在Tomcat中部署)
  3. Daily Scrum 12.18
  4. bootstrap之消息提示
  5. SVN客户端常用命令
  6. 一致性Hash算法在Memcached中的应用
  7. 字符串(LCT,后缀自动机):BZOJ 2555 SubString
  8. DEV GridControl 根据单元格值改变背景色
  9. 切图教程,APP切图实例
  10. A 01 如何理解会计中的借和贷
  11. Java锁Synchronized对象锁和类锁区别
  12. Python 的第一个小程序
  13. python待学习内容
  14. centos7证书安全登录
  15. 通过阿里云命令行工具 aliyuncli 购买服务器
  16. Python环境下如何安装爬虫需求的一些库
  17. OPENGL: WHY IS YOUR CODE PRODUCING A BLACK WINDOW?
  18. 支付宝支付-PC电脑网站支付
  19. 【Java集合的详细研究1】Collections类常用方法总结
  20. 终于,我们的新产品Fotor Slideshow Maker上线了!!

热门文章

  1. spring mvc 静态资源版本控制
  2. Spring源码解析 - AbstractBeanFactory 实现接口与父类分析
  3. (深搜)Sum It Up -- poj --1564
  4. (匹配)Dolls --HDU --4160
  5. hdu 5062 单峰数(12321)的个数
  6. web问题
  7. 教程-Delphi调用百度地图API(XE8+WIN7)
  8. 【算法30】从数组中选择k组长度为m的子数组,要求其和最小
  9. 让Easy UI 的DataGrid直接内嵌的JSON对象,并重写form load 方法
  10. 微软儿童编程技术,kodu(酷豆)为儿童创造一个游戏世界