题解 | #单链表的排序#

单链表的排序

http://www.nowcoder.com/practice/f23604257af94d939848729b1a5cda08

import java.util.*;

/*
 * public class ListNode {
 *   int val;
 *   ListNode next = null;
 * }
 */

public class Solution {
    /**
     * 
     * @param head ListNode类 the head node
     * @return ListNode类
     * @method 单链表切分为两个链表,再排序,再合并有序链表
     */
    public ListNode sortInList (ListNode head) {
        if (head == null || head.next == null)
            return head;
        // write code here
        // 1. 切分链表
        ListNode slow = head , fast = head.next;
        while(fast != null && fast.next != null ){
            fast = fast.next.next;
            slow = slow.next;
        }
        ListNode head2= slow.next;
        slow.next = null;

        // 2.排序
        ListNode left = sortInList(head);
        ListNode right = sortInList(head2);

        // 3.合并两个有序链表
        ListNode ans = new ListNode(-1);
        ListNode res = ans;
        while(left != null && right != null){
            if(left.val <= right.val) {
                res.next = new ListNode(left.val);
                left = left.next;
            }else {
                res.next = new ListNode(right.val);
                right = right.next;
            }
            res = res.next;
        }
        if(left == null){ res.next = right;}
        if(right == null){ res.next = left;}

        return ans.next;


    }
}
全部评论

相关推荐

gcniz:一天写两千行你闹呢
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务