题解 | #单链表的排序#
单链表的排序
https://www.nowcoder.com/practice/f23604257af94d939848729b1a5cda08
import java.util.*; /* * public class ListNode { * int val; * ListNode next = null; * } */ // 空间复杂度nlogn就用归并排序,归并分为两部分,拆分和合并 public class Solution { /** * * @param head ListNode类 the head node * @return ListNode类 */ public ListNode sortInList (ListNode head) { // 首先判断是否为空或一位 if(head == null || head.next == null){ return head; } // 拆分(利用双指针在中心点拆分,最后slow所在位置就是中点,断开) ListNode slow = head; ListNode fast = head.next; while(fast != null && fast.next != null){ slow = slow.next; fast = fast.next.next; } ListNode right = slow.next; // 这里用一个right记录右侧的head slow.next = null; return mergeSort(sortInList(head),sortInList(right)); } // 归并排序 public ListNode mergeSort(ListNode head1,ListNode head2){ // 直接用一个ListNode引出一条新的链表记录数据 ListNode head = new ListNode(-999); ListNode followHead = head; while(head1 != null && head2 != null){ if(head1.val > head2.val){ followHead.next = head2; head2 = head2.next; }else{ followHead.next = head1; head1 = head1.next; } followHead = followHead.next; } followHead.next = head1==null ? head2 : head1; return head.next; } }