题解 | #牛群的身高排序#
牛群的身高排序
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) {
// write code here
if (head == null || head.next == null) {
return head; // 链表为空或只有一个节点,无需排序
}
// 找到链表中间节点,分割成两部分
ListNode mid = findMiddle(head);
ListNode left = head;
ListNode right = mid.next;
mid.next = null;
// 递归对左右两部分链表进行排序
ListNode sortedLeft = sortList(left);
ListNode sortedRight = sortList(right);
// 合并已排序的左右两部分链表
return merge(sortedLeft, sortedRight);
}
private ListNode findMiddle(ListNode head) {
ListNode slow = head;
ListNode fast = head;
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 cur = dummy;
while (left != null && right != null) {
if (left.val < right.val) {
cur.next = left;
left = left.next;
} else {
cur.next = right;
right = right.next;
}
cur = cur.next;
}
if (left != null) {
cur.next = left;
}
if (right != null) {
cur.next = right;
}
return dummy.next;
}
}
题目考察的知识点:
链表排序。
解题方法分析:
- 链表的排序可以使用归并排序(Merge Sort)的思想来实现。归并排序是一种稳定的排序算法,适用于链表排序的场景。
- 对于链表排序,可以将链表不断地二分,然后将分割后的两个子链表进行合并。
- 合并两个有序链表可以使用迭代或递归的方式。
- 在迭代的方式中,创建一个新的链表作为结果链表,然后依次比较两个链表的头节点,将较小的节点加入结果链表,然后移动指针。
- 在递归的方式中,将问题分解为合并两个子问题,即合并左半部分和合并右半部分。
查看16道真题和解析