LeetCode Sort List 解题报告
2014-02-08 15:31
344 查看
Sort a linked list in O(n log n) time using constant space complexity.
http://oj.leetcode.com/problems/sort-list/
解题报告:就是对一个链表进行归并排序。
主要考察3个知识点,
知识点1:归并排序的整体思想
知识点2:找到一个链表的中间节点的方法
知识点3:合并两个已排好序的链表为一个新的有序链表
归并排序的基本思想是:找到链表的middle节点,然后递归对前半部分和后半部分分别进行归并排序,最后对两个以排好序的链表进行Merge。
AC代码: https://github.com/tanglu/Leetcode/blob/master/sortList.java
http://oj.leetcode.com/problems/sort-list/
解题报告:就是对一个链表进行归并排序。
主要考察3个知识点,
知识点1:归并排序的整体思想
知识点2:找到一个链表的中间节点的方法
知识点3:合并两个已排好序的链表为一个新的有序链表
归并排序的基本思想是:找到链表的middle节点,然后递归对前半部分和后半部分分别进行归并排序,最后对两个以排好序的链表进行Merge。
AC代码: https://github.com/tanglu/Leetcode/blob/master/sortList.java
/** * 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; } }
相关文章推荐
- LeetCode 解题报告 Sort List
- [Leetcode] 148. Sort List 解题报告
- LeetCode解题报告—— Rotate List & Set Matrix Zeroes & Sort Colors
- leetCode解题报告之Insertion Sort List
- 景岁的Leetcode解题报告:147.Insertion Sort List (Java)
- [leetcode] 148. Sort List 解题报告
- [LeetCode]Sort List,解题报告
- leetcode 148. Sort List 解题报告
- LeetCode Sort List 解题报告
- 【LeetCode】Sort List 解题报告(对链表进行归并排序)
- LeetCode—Sort List解题报告
- 【LeetCode】Insertion Sort List 解题报告
- Leetcode Sort List 解题报告
- LeetCode: Sort List 解题报告
- Leetcode Insertion Sort List 解题报告
- LeetCode—Insertion Sort List 解题报告
- LeetCode 148. Sort List 解题报告(归并排序小结)
- [leetcode] 147. Insertion Sort List 解题报告
- leetCode解题报告之Sort List
- [Leetcode] 147. Insertion Sort List 解题报告