题解 | #单链表的排序# 归并排序,只使用递归栈空间
单链表的排序
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 slow = head; ListNode tail = slow; ListNode fast = head; while (fast != null) { tail = slow; slow = slow.next; fast = fast.next; if (fast != null) { fast = fast.next; } } // 很关键,把链表分成两段,上一段指向null tail.next = null; // 分别排序两部分链表 ListNode sortedLeft = sortInList(head); ListNode sortedRight = sortInList(slow); // 合并排序链表 ListNode hair = new ListNode(0); ListNode pointer = hair; while (sortedLeft != null && sortedRight != null) { if (sortedLeft.val < sortedRight.val) { pointer.next = sortedLeft; sortedLeft = sortedLeft.next; pointer = pointer.next; } else { pointer.next = sortedRight; sortedRight = sortedRight.next; pointer = pointer.next; } } if (sortedLeft != null) { pointer.next = sortedLeft; } if (sortedRight != null) { pointer.next = sortedRight; } return hair.next; } }