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

[LeetCode] 148. Sort List

时间:2017-06-13 16:48:30      阅读:120      评论:0      收藏:0      [点我收藏+]

标签:int   next   com   merge   new   class   tco   link   https   

https://leetcode.com/problems/sort-list/

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

 

[LeetCode] 148. Sort List

标签:int   next   com   merge   new   class   tco   link   https   

原文地址:http://www.cnblogs.com/chencode/p/sort-list.html

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