题解 | #单链表的排序#
单链表的排序
https://www.nowcoder.com/practice/f23604257af94d939848729b1a5cda08
import java.util.*; /* * public class ListNode { * int val; * ListNode next = null; * public ListNode(int val) { * this.val = val; * } * } */ public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param head ListNode类 the head node * @return ListNode类 */ public ListNode sortInList(ListNode head) { if (head == null || head.next == null) { return head; // 只有一个节点或空,直接返回 } // 使用快慢指针将链表分为两半 ListNode mid = getMiddle(head); ListNode rightHead = mid.next; mid.next = null; // 断开链表,形成两个独立部分 // 递归排序左右两部分 ListNode left = sortInList(head); ListNode right = sortInList(rightHead); // 合并两个已排序的链表 return mergeTwoLists(left, right); } // 获取链表中间节点(快慢指针法) private ListNode getMiddle(ListNode head) { ListNode slow = head; ListNode fast = head.next; while (fast != null && fast.next != null) { slow = slow.next; fast = fast.next.next; } return slow; // 返回中间节点 } // 合并两个已排序链表 private ListNode mergeTwoLists(ListNode l1, ListNode l2) { ListNode dummy = new ListNode(-1); ListNode current = dummy; while (l1 != null && l2 != null) { if (l1.val <= l2.val) { current.next = l1; l1 = l1.next; } else { current.next = l2; l2 = l2.next; } current = current.next; } // 若有剩余节点,直接链接到结果链表后面 if (l1 != null) { current.next = l1; } else { current.next = l2; } return dummy.next; } }#我的实习求职记录#