148. Sort List
2016-04-18 19:50
423 查看
Sort List
Sort a linked list inO(n log n)time using constant space complexity.
对一个链表排序,要求
O(n log n)的时间复杂度。
因为Java提供了
O(n log 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; } ListNode temp = head; List<ListNode> list = new ArrayList<>(); //把链表中的每一项添加到一个List中,然后用Collections.sort方法排序 while (temp != null) { list.add(temp); temp = temp.next; } Comparator<ListNode> comparator = new Comparator<ListNode>() { @Override public int compare(ListNode o1, ListNode o2) { return o1.val - o2.val; } }; Collections.sort(list, comparator); ListNode first = null; //使自己定义的List中每一项ListNode对象的next指针指向该项的下一项 for (int i = list.size() - 1; i > 0 ; i--) { //如果是链表中的最后一项,则让链表尾部指向null,否则会指向原链表中的未知位置 if (i == list.size() - 1) { list.get(i).next = null; } ListNode pre = list.get(i - 1); pre.next = list.get(i); //返回头结点 if (i == 1) { first = list.get(i - 1); } } return first; } }
相关文章推荐
- String、StringBuffer与StringBuilder之间区别
- OOM详解
- 第一冲刺阶段站立会议02
- innerHTML和innerText的区别
- 一个TextView显示多个颜色
- ViewPager无限自动轮播
- TOYS--POJ2318
- <松本行弘的程序世界> 读书笔记
- 离散化+线段树 codefores555C Case of Chocolate
- uva 10304 - Optimal Binary Search Tree(区间dp)
- Linux操作提示:“Cant open file for writing”或“operation not permitted”的解决办法
- 嵌入式平台下的ldd
- CPU acceleration status:HAXM must be updated(version 1.1.1<6.0.1)
- 获得执行jar的运行路径
- 中国大陆CDN的测量与分析
- Labview队列操作
- hdu 1142 最短路径+dfs记忆化搜索
- 【小笨鸟看JDK1.7集合源码之一】JAVA集合整体框架
- codeforces_304C_数学题
- iOS:实现图片的无限轮播之使用第三方库SDCycleScrollView