题目
思路
由于要实现O(nlogn)的时间复杂度,所以需要使用归并排序来进行排序,归并排序的每次找到链表的中点,将链表切割成两段,直到长度为1,此时在合并每段代码
代码
public ListNode sortList(ListNode head) {if (head == null || head.next == null) return head;return mergeSort(head);}public ListNode mergeSort(ListNode head) {if (head.next == null) return head;ListNode fast = head.next, slow = head;while (fast != null && fast.next != null) {fast = fast.next.next;slow = slow.next;}fast = slow.next;slow.next = null;return merge(mergeSort(head), mergeSort(fast));}public ListNode merge(ListNode p1, ListNode p2) {ListNode dummy = new ListNode(0);ListNode p = dummy;while (p1 != null && p2 != null) {if (p1.val < p2.val) {p.next = p1;p1 = p1.next;} else {p.next = p2;p2 = p2.next;}p = p.next;}p.next = p1 == null ? p2 : p1;return dummy.next;}
