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
-
-
-
-
-
-
-
-
-
-
-
- public class Solution {
-
- 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));
- }
-
-
- 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;
- }
- }
转载地址:
http://blog.youkuaiyun.com/worldwindjp/article/details/18986737