码迷,mamicode.com
首页 > 其他好文 > 详细

Sort List

时间:2015-03-11 21:30:59      阅读:165      评论:0      收藏:0      [点我收藏+]

标签:

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

方法的图形化证明:

技术分享

Sort List

标签:

原文地址:http://www.cnblogs.com/sunshisonghit/p/4330888.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!