[LeetCode] sort-list
来源:互联网 发布:伊朗 知乎 编辑:程序博客网 时间:2024/06/06 14:15
sort-list
题目描述
Sort a linked list in O(n log n) time using constant space complexity.
链表排序。。要求用O(n log n)的复杂度。好像只有归并排序比较适合
把链表分成两部分的时候用快慢指针:当快指针遍历结束后,慢指针刚到中间。
/** * Definition for singly-linked list. * class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */public class Solution { public ListNode sortList(ListNode head) { if(head==null||head.next==null) return head; ListNode slow = head; ListNode fast = head; while(fast.next!=null&&fast.next.next!=null){ slow = slow.next; fast = fast.next.next; } fast = slow.next; slow.next = null; ListNode l = sortList(head); ListNode r = sortList(fast); return merge(l, r); } public ListNode merge(ListNode l,ListNode r){ if(l==null) return r; if(r==null) return l; ListNode head1 = new ListNode(0); ListNode temp = head1; while(l!=null&&r!=null){ if(l.val<r.val){ temp.next = l; l = l.next; }else{ temp.next = r; r = r.next; } temp = temp.next; if(l!=null){ temp.next = l; } if(r!=null){ temp.next = r; } } return head1.next; }}
0 0
- [leetcode][list][sort] Sort List
- Insertion Sort List | leetcode
- Leetcode: Insertion Sort List
- [LeetCode] Insertion Sort List
- Leetcode: Insertion Sort List
- Leetcode: Sort List
- Sort List | leetcode
- leetcode-Sort List
- leetcode-Insertion Sort List
- LeetCode题解:Sort List
- leetcode 134: Sort List
- [LeetCode]Sort List
- [LeetCode]Insertion Sort List
- [LeetCode] Sort List
- 【LeetCode】Insertion Sort List
- leetCode - Sort List
- LeetCode | Insertion Sort List
- LeetCode - Insertion Sort List
- JAVA学习代码——进制转换
- jquery使用ajax提交表单
- Java经典实例代码
- POJ 2155 Matrix(二维树状数组)
- 夏令营day9总结
- [LeetCode] sort-list
- 【垂直搜索引擎搭建02】heritrix启动
- poj 3259 Wormholes
- 不用category.HOME启动Launcher
- linux_windows双系统_方向下键不能用怎么办
- 深入研究:内存&字符串&结构体&共用体&枚举
- English Daily - August 12,2016-Letty
- JDBC基础编程
- A+B