leetcode---SortList
来源:互联网 发布:python 经典书籍 知乎 编辑:程序博客网 时间:2024/06/06 07:23
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 { public ListNode sortList(ListNode head) { if(head==null||head.next==null) return head; ListNode slow=head,fast=head.next.next; while(fast!=null&&fast.next!=null){ slow=slow.next; fast=fast.next.next; } //找到中间的节点slow ListNode p1=sortList(slow.next); slow.next=null; ListNode p2=sortList(head); return merge(p1,p2); } public ListNode merge(ListNode i,ListNode j){ ListNode p,dummy=new ListNode(0); p=dummy; while(i!=null&&j!=null){ if(i.val<j.val){ p.next=i; i=i.next; } else{ p.next=j; j=j.next; } p=p.next; } p.next = (i==null?j:i);//合并剩余的 return dummy.next; }}
0 0
- leetcode || sortlist
- leetcode--SortList
- leetcode---SortList
- leetcode题目解答---- SortList
- leetcode 148 sortList
- Leetcode 148 SortList
- leetcode 148 sortlist
- SortList
- SortList
- SortList
- LeetCode 148: SortList, 206:Reverse linked list
- sortlist.c
- Insert SortList
- 刷题——SortList
- SortList 单链表排序 要求复杂度O(NlgN)
- ASP.net 中Queue,Stack,Hashtable,Sortlist一些简单用法
- SortList非泛型和泛型遍历输出形式
- sortList and Lowest Common Ancestor of a Binary Search Tree
- OI算法汇总[大纲]
- 【BZOJ4385】[POI2015]Wilcze doły【单调队列】【前缀和】【Two Pointers】
- android---极光推送初步了解
- Critical Links(连通图 桥)
- IOS中sqlite数据库利用bold类型存储与读取字典
- leetcode---SortList
- 多传感器数据融合算法---9轴惯性传感器
- 有关QWidget的关闭close()
- Zigbee之旅(三):几个重要的CC2430基础实验——外部中断
- O'Reilly-现代php译文(1)
- CentOs中安装和配置vsftp简明教程
- 计算机视觉领域的一些牛人博客,研究机构等的网站链接
- 关于mybatis的insertintoselect命令未结束问题
- [C++]高精度 bign (重载运算符版本)