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

LeetCode-Sort List

时间:2015-03-09 23:54:04      阅读:212      评论:0      收藏:0      [点我收藏+]

标签:

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

这题的时间复杂度要求是O(n logn),很容易想到用mergeSort来解。

/**
 * Definition for singly-linked list.
 * class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
 
public class Solution {
    
    public ListNode merge(ListNode head1, ListNode head2){
        ListNode dummy = new ListNode(-1);
        ListNode tail = dummy;
        while(head1 != null && head2 != null){
            if(head1.val < head2.val){
                tail.next = head1;
                head1 = head1.next;
            }
            else {
                tail.next = head2;
                head2 = head2.next;
            }
            tail = tail.next;
        }
        if(head1 != null){
            tail.next = head1;
        }
        if(head2 != null){
            tail.next = head2;
        }

        return dummy.next;
        
    }
    
    
    public ListNode findMid(ListNode head){
        ListNode slow = head;
        ListNode fast = head.next;//instead of = head to ensure slow is in the mid position
        while(fast != null && fast.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 mid = findMid(head);
        ListNode right = sortList(mid.next);
        mid.next=null;
        ListNode left = sortList(head);
        
        return  merge(left,right);
        
        
    }

    
}

其中值得注意的是,

1.在merge function里dummy前置节点和tail的作用,

2.以及findMin里ListNode fast = head.next的作用,

3.sortList中mid.next = null 的作用

LeetCode-Sort List

标签:

原文地址:http://www.cnblogs.com/incrediblechangshuo/p/4324822.html

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