Leetcode-Sort List
来源:互联网 发布:泰拉瑞亚作弊软件 编辑:程序博客网 时间:2024/05/01 00:04
Sort a linked list in O(n log n) time using constant space complexity.
/** * Definition for singly-linked list. * class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */public class Solution { //use the fast and slow pointer to get the middle of a ListNode ListNode getMiddleOfList(ListNode head) { ListNode slow = head; ListNode fast = head; while(fast.next!=null&&fast.next.next!=null) { slow = slow.next; fast = fast.next.next; } return slow; } public ListNode sortList(ListNode head) { if(head==null||head.next==null) { return head; } ListNode middle = getMiddleOfList(head); ListNode next = middle.next; middle.next = null; return mergeList(sortList(head), sortList(next)); } //merge the two sorted list ListNode mergeList(ListNode a, ListNode b) { ListNode dummyHead = new ListNode(-1); ListNode curr = dummyHead; while(a!=null&&b!=null) { if(a.val<=b.val) { curr.next=a;a=a.next; } else { curr.next=b;b=b.next; } curr = curr.next; } curr.next = a!=null?a:b; return dummyHead.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
- kali 与 windows 双系统的 grub 设置
- 联合主键、非主键查询以及去重
- 重新建站记:下
- Microsoft JScript 运行时错误: Sys.WebForms.PageRequestManagerParserErrorException
- JS计算天数差
- Leetcode-Sort List
- 混淆网络和词格或者字格
- rman初级知识(读书笔记)
- oracle字符替换
- C# 自定义类 汉化Dex10.2.5插件
- UNIX系统开发-gcc参数详解
- poj 2524 Ubiquitous Religions
- 进程间数据通信方式和特点
- UIView animations with autolayout