首页 > 其他 > 详细

148. Sort List

时间:2016-04-16 16:57:16      阅读:218      评论:0      收藏:0      [点我收藏+]

方法1:归并排序思路:

(1)设计一个寻找中间节点的函数;(2)设计一个归并两个已经有序的函数;(3) 主函数;

其中第一个函数思想:是在109题转换成BST当中使用的那样,同时也是快慢链表解决环形链表当中的设计一样的思路!

public class Solution {
    private ListNode findMidNode(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;
    }
    private ListNode merge(ListNode head1, ListNode head2){
        ListNode dummy = new ListNode(0);
        ListNode index = dummy;
        while(head1 != null && head2 != null)
        {
            if(head1.val < head2.val)
              {
                  index.next = head1;
                  head1 = head1.next;
              }
             else
              {
                  index.next = head2;
                  head2 = head2.next;
              }
              index = index.next;
        }
        if(head1 != null)  index.next = head1;
        else               index.next = head2;
        return dummy.next;
    }
    public ListNode sortList(ListNode head) {
        if(head == null || head.next == null){
            return head;
        }
        ListNode mid = findMidNode(head);
        ListNode left = sortList(mid.next);
        mid.next = null;
        ListNode right = sortList(head);
        return merge(left,right);
    }
}

 

148. Sort List

原文:http://www.cnblogs.com/ProWhalen/p/5398457.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!