[leedcode 148] Sort List
2015-08-01 17:58
288 查看
Sort a linked list in O(n log n) time using constant space complexity.
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ public class Solution { /* Like the merge sort, we can do recursively: (1) Split the list (slow fast pointers) (2) sort the first part (merge sort) (3) sort the second part (merge sort) (4) merge the two parts (merge two sorted lists) 注意函数返回值 */ public ListNode sortList(ListNode head) { if(head==null||head.next==null) return head; ListNode p= mergeSort(head); return p; } public ListNode mergeSort(ListNode head){ if(head==null||head.next==null) return head; ListNode mid=getMiddleNode(head); ListNode p=mid.next; mid.next=null; ListNode first=mergeSort(head); ListNode second=mergeSort(p); return mergeTwoLists(first,second); } public ListNode getMiddleNode(ListNode head){ ListNode newHead=new ListNode(-1); newHead.next=head; ListNode fast=head; ListNode slow=newHead; while(fast!=null&&fast.next!=null){ fast=fast.next.next; slow=slow.next; } return slow; } public ListNode mergeTwoLists(ListNode first,ListNode second){ ListNode newHead=new ListNode(-1); ListNode p=newHead; while(first!=null&&second!=null){ if(first.val<second.val){ p.next=first; p=first; first=first.next; }else{ p.next=second; p=second; second=second.next; } } if(first!=null){ p.next=first; } if(second!=null){ p.next=second; } return newHead.next; } }
相关文章推荐
- POJ 1144 Network
- IOS开发UI基础UIPageControl的属性
- 使用UIScrollView 结合 UIImageView 实现图片循环滚动
- 【排序】快速排序模板
- oop
- 构建使用 Azure 网站的云
- Assign the task---hdu3974
- UVALive 5532 King(差分约束,spfa)
- php-高级(错误处理和异常处理)
- Android图片缓存库使用经验总结
- HDU 4355 数轴上的点找使Si^3*Wi最小的和-浮点数三分
- Activity数据传输--Intent显示、隐式、不同应用之间启动
- java中return的作用
- c 总结
- 用JavaScript验证表单
- TP
- IOS开发UI基础UIPikerView的属性
- Integer to Roman
- CSS中的文本属性学习指南
- error LNK2019: 无法解析的外部符号 __imp__CryptBinaryToStringA@20