【链表】Sort List(归并排序)
2016-01-19 16:53
441 查看
题目:
Sort a linked list in O(n log n) time using constant space complexity.
思路:
nlogn的排序有快速排序、归并排序、堆排序。双向链表用快排比较适合,堆排序也可以用于链表,单向链表适合用归并排序。
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; }
相关文章推荐
- java
- 转 python全局变量
- apache+tomcat集群出现的两次请求问题解决方案
- Android版本随记
- Android MVP模式
- main函数传参数以及执行过程
- unsupported_grant_type
- Android运行环境Dalvik和ART的比较
- 轮播图切换 纯html+js+css
- Django实践:个人博客系统(第八章 admin的配置)
- 条件表达式工具类
- THE HANDLER_READ_* STATUS VARIABLES
- 关于将vector以及string传递给较老的api的问题
- 如何查看Windows激活信息
- 拦截器的方法介绍(三)
- ios已上架的APP更新,使用core data的需要升级core Data数据库,这样做
- 15 个必知的 Android 开发者选项
- 检查Mac电脑是32位还是64位运行以及修改方法
- C++经典面试题
- ERROR 1820 (HY000): You must SET PASSWORD before executing this