题解 | 单链表的排序
单链表的排序
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类 */ // 对一个无序单链表,对其按升序排序 // 空间复杂度O(n),时间复杂度O(nlogn);应该使用归并排序 public ListNode sortInList (ListNode head) { if(head == null || head.next == null) return head; // write code here ListNode left = head; ListNode mid = head.next; ListNode right = head.next.next; // 右边的指针到达末尾时,中间的指针指向该段链表的中间 while(right != null && right.next != null){ left = left.next; mid = mid.next; right = right.next.next; } // 左边指针指向左段的左右一个节点,从这里断开 left.next = null; return merge(sortInList(head),sortInList(mid)); } public ListNode merge(ListNode pHead1, ListNode pHead2){ if(pHead1 == null) return pHead2; if(pHead2 == null) return pHead1; ListNode head = new ListNode(0); ListNode cur = head; while(pHead1 != null && pHead2 != null){ if(pHead1.val <= pHead2.val){ cur.next = pHead1; pHead1 = pHead1.next; }else{ cur.next = pHead2; pHead2 = pHead2.next; } cur = cur.next; } if(pHead1 != null) cur.next = pHead1; else cur.next = pHead2; return head.next; } }