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

排序,要求是O(nlog(n))的时间复杂度和常数的空间复杂度,那么就使用归并就可以了。

/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution { public ListNode sortList(ListNode head) {
if( head == null || head.next == null)
return head; int size = 1;
ListNode start = new ListNode(0);
start.next = head; while( true ){
ListNode node1 = start;
ListNode node2 = start.next;
for( int i = 0 ; i < size && node2!=null;i++){
node2 = node2.next;
} if( node2 == null )
break;
ListNode nnn = start.next; while( node2 != null ){
node1 = helper(node1,node2,size);
if( node1 == null )
break;
node2 = node1.next;
for( int i = 0 ; i< size && node2 != null;i++){
node2 = node2.next;
}
}
size*=2;
}
return start.next;
} public ListNode helper(ListNode node1,ListNode node2,int size){ int num1 = 0,num2 = 0; ListNode node = null; if( node1.next.val < node2.val ){
node = node1.next;
node1 = node1.next.next;
num1++;
}else{
ListNode nn = node1.next;
node1.next = node2;
node1 = nn;
node = node2;
node2 = node2.next;
num2++;
} while( num1 < size && num2 < size && node1 != null && node2 != null){ if( node1.val < node2.val ){
node.next = node1;
node = node1;
node1 = node1.next;
num1++;
}else{
node.next = node2;
node = node2;
node2 = node2.next;
num2++;
}
}
while( num1 < size && node1 != null){
node.next = node1;
node = node1;
node1 = node1.next;
num1++;
} while( num2 < size && node2 != null){
node.next = node2;
node = node2;
node2 = node2.next;
num2++;
}
node.next = node2;
return node; }
}

最新文章

  1. Worktile协同特色之一:无处不在的关注
  2. xamarin 手机顶部状态栏
  3. 虚拟机利用Host-only实现在不插网线的情况下,虚拟机与主机实现双向通信,实现ssh连接以及samba服务实现共享
  4. 使用TCMalloc的堆栈检查
  5. Iterator&lt;转&gt;
  6. 算法:C++排列组合
  7. jquery的小插件(按钮抖动)——衍生QQ窗口抖动
  8. memcached原理全面剖析
  9. 我不知道你是在一个多线程out该--【ITOO】
  10. 字符函数库 - cctype 和 climits 中的符号常量
  11. C++第二天
  12. 《JS权威指南学习总结--第十一章子集和扩展》
  13. centos6.8 docker0: iptables: No chain/target/match by that name
  14. 向量 dot cross product 点积叉积 几何意义
  15. AJAX工作原理与缺点
  16. Spring Boot Log4j2 日志学习
  17. python string.py 源码分析 二:capwords
  18. day 06云计算的三种服务模式:IaaS,PaaS和SaaS
  19. 嵌入式linux查看磁盘占用情况df -h
  20. SQL记录-PLSQL日期与时间

热门文章

  1. string.format
  2. asp.net mvc 2.o 中使用JQuery.uploadify
  3. 查看UI调试界面利器 revealapp
  4. 使用AWT组件实现验证码功能
  5. Great writers inspire
  6. 【参考文献1】Word2010删除引用参考文献留下的横线
  7. Coudera-Manager/CDH的安装和部署
  8. json_decode 与 json_encode 的区别
  9. XML元素和结点的区别
  10. Ubuntu 14.10 下安装Synergy,不同电脑之间公用一套键盘鼠标