sort-list
2015-06-27 11:39
447 查看
中等 链表排序
28%通过
在O(nlogn)时间复杂度和常数级的空间复杂度下给链表排序。
您在真实的面试中是否遇到过这个题?
Yes
样例
给出1-3->2->null,给它排序变成1->2->3->null
/** * Definition for ListNode. * public class ListNode { * int val; * ListNode next; * ListNode(int val) { * this.val = val; * this.next = null; * } * } */ public class Solution { /** * @param head: The head of linked list. * @return: You should return the head of the sorted linked list, using constant space complexity. */ 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); } }
相关文章推荐
- 堆排序
- Node.js
- 可变参数的函数
- 在二维数组中查找有无此数(非重新排序)
- html中必备标签及引用W3C标准
- CF 552C 进制转换
- 用L脚本语言实现"L脚本语言控制台"
- 高级指针
- 关于即时通讯系统中消息发送、转发、展示、提示等专利初探
- 网页引用外部js脚本文件时必须是(转)
- OpenStack概念
- 6.27
- Unity3D资源存放笔记
- Eclipse debug 断点不能调试 ,Eclipse Unable to install breakpoint in 解决办法
- Miss,Ms. Mrs. Mr. Dr.区别
- L脚本语言实现文件加解密
- Ubuntu下面安装eclipse for c++
- Android开发中 软件盘将布局遮住的问题
- 计数排序(C语言版本)
- qca4004模块离线不上线原因分析