归并排序---Sort List
来源:互联网 发布:json美化 编辑:程序博客网 时间:2024/05/17 06:55
Sort a linked list in O(n log n) time using constant space complexity.
Have you met this question in a real interview? Yes
Example
Given 1-3->2->null, sort it to 1->2->3->null.
Tags Expand
Related Problems Expand
/** * Definition for ListNode. * public class ListNode { * int val; * ListNode next; * ListNode(int val) { * this.val = val; * this.next = null; * } * } */ public class Solution { private ListNode findMiddle(ListNode head) { ListNode slow = head, fast = head.next; while (fast != null && fast.next != null) { fast = fast.next.next; slow = slow.next; } return slow; } private ListNode merge(ListNode head1, ListNode head2) { ListNode dummy = new ListNode(0); ListNode tail = dummy; while (head1 != null && head2 != null) { if (head1.val < head2.val) { tail.next = head1; head1 = head1.next; } else { tail.next = head2; head2 = head2.next; } tail = tail.next; } if (head1 != null) { tail.next = head1; } else { tail.next = head2; } return dummy.next; } public ListNode sortList(ListNode head) { if (head == null || head.next == null) { return head; } ListNode mid = findMiddle(head); ListNode right = sortList(mid.next); mid.next = null; ListNode left = sortList(head); return merge(left, right); }}
0 0
- 归并排序---Sort List
- sort list leetcode (归并排序)
- Leetcode Sort List 链表归并排序
- Leetcode:Sort List 对单链表归并排序
- 【leetcode 单链表归并排序】Sort List
- 【LeetCode】 sort list 单链表的归并排序
- Sort List 归并排序链表
- [leetcode] 134 Sort List (链表 & 归并排序)
- LeetCode Sort List(单链表归并排序)
- 148. Sort List 链表归并排序
- Sort List —— 归并排序
- Sort List(二路归并排序)
- Leetcode: Sort List - 归并
- Sort List——链表的快速/归并排序
- 链表的二路归并排序 Sort List
- leetcode:Sort List(链表的归并排序)
- [C++]LeetCode: 125 Sort List (归并排序链表)
- LeetCode Sort List 链表的归并排序
- Android之服务(四)前台服务
- python学习笔记一
- DBGridEh本地过滤或排序的功能
- ALSA声卡驱动中的DAPM详解之七:dapm事件机制(dapm event)
- Python基础教程笔记——使用字符串
- 归并排序---Sort List
- iOS右划返回手势
- 反素数深度分析 (转)
- CMM 开发故障小结
- NYoj52 无聊的小明
- Java笔记18:JUnit单元测试
- Android 检查运行慢原因和分析
- pageRank
- Linux系统抓包命令tcpdump使用实例