题解 | #牛群的身高排序#
牛群的身高排序
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; } }
设计知识点:链表排序,递归