Sort List

Sort List

问题:

Sort a linked list in O(n log n) time using constant space complexity.

思路:

  归并排序

我的代码:

public class Solution {
    public ListNode sortList(ListNode head) {
        if(head == null) return null;
        if(head.next == null)   return head;
        ListNode mid = getMiddle(head);
        ListNode right = sortList(mid.next);
        mid.next = null;
        ListNode left = sortList(head);
        return mergeList(left,right);
    }
    public ListNode getMiddle(ListNode head)
    {
        ListNode slow = head;
        ListNode fast = head.next;
        while(fast != null && fast.next != null)
        {
            slow = slow.next;
            fast = fast.next.next;
        }
        return slow;
    }
    public ListNode mergeList(ListNode head1, ListNode head2)
    {
        ListNode dummy = new ListNode(-1);
        ListNode head = dummy;
        while(head1 != null && head2 != null)
        {
            if(head1.val < head2.val)
            {
                dummy.next = head1;
                head1 = head1.next;
            }
            else
            {
                dummy.next = head2;
                head2 = head2.next;
            }
            dummy = dummy.next;
        }
        if(head1 != null)   dummy.next = head1;
        if(head2 != null)   dummy.next = head2;
        return head.next;
    }
}
View Code

学习之处:

  • 对于链表求中间位置,如果用长度进行遍历的控制的话,一来浪费时间,二来太难确定数目大小,访问位置合适不合适
  • 代码中用的是slow fast 方法得到mid的位置,简单易行,指的以后参考学习
  • 对于left和right 分别sort也有讲究,right需在前,待mid.next = null之后,方可sort left要不进入了死循环了。

slow fast方法得mid模板

public ListNode getMiddle(ListNode head)
    {
        ListNode slow = head;
        ListNode fast = head.next;
        while(fast != null && fast.next != null)
        {
            slow = slow.next;
            fast = fast.next.next;
        }
        return slow;
    }
View Code

方法的图形化证明:

posted on 2015-03-11 20:31  zhouzhou0615  阅读(153)  评论(0编辑  收藏  举报

导航