题解 | #牛群的身高排序#

牛群的身高排序

https://www.nowcoder.com/practice/9ce3d60e478744c09768d1aa256bfdb5

import java.util.*;

/*
 * public class ListNode {
 *   int val;
 *   ListNode next = null;
 *   public ListNode(int val) {
 *     this.val = val;
 *   }
 * }
 */

public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param head ListNode类 
     * @return ListNode类
     */
    public ListNode sortList (ListNode head) {
        if(head==null||head.next==null){
            return head;
        }
        ListNode middle = findMiddle(head);
        ListNode secondHalf = middle.next;
        middle.next = null;
        ListNode left = sortList(head);
        ListNode right = sortList(secondHalf);
        return merge(left,right);
        // write code here
    }
    private ListNode findMiddle(ListNode head){
        ListNode node = new ListNode(-1);
        node = head;
        ListNode slow = node;
        ListNode fast = node;
        while(fast!=null&&fast.next!=null&&fast.next.next!=null){
            slow = slow.next;
            fast = fast.next.next;
        }
        return slow;
    }
    private ListNode merge(ListNode left,ListNode right){
        ListNode dummy = new ListNode(0);
        ListNode current = dummy;
        while(left!=null&&right!=null){
            if(left.val<right.val){
                current.next = left;
                left = left.next;
            }else{
                current.next = right;
                right = right.next;
            }
            current = current.next;
        }
        if(left!=null){
            current.next = left;
        }
        if(right!=null){
            current.next = right;
        }
        while(current.next!=null){
            current = current.next;
        }
        return dummy.next;
    }
}

设计知识点:链表排序,递归

全部评论

相关推荐

10-15 16:27
门头沟学院 C++
LeoMoon:建议问一下是不是你给他付钱😅😅
点赞 评论 收藏
分享
我也曾抱有希望:说的好直白
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务