题解 | #单链表的排序#
单链表的排序
https://www.nowcoder.com/practice/f23604257af94d939848729b1a5cda08
/* * function ListNode(x){ * this.val = x; * this.next = null; * } */ /** * * @param head ListNode类 the head node * @return ListNode类 */ function sortInList(head) { // write code here let arr = []; while (head) { arr.push(head.val); head = head.next; } quickSort(arr, 0, arr.length - 1); let res = new ListNode(-1), t = res; for (let i = 0; i < arr.length; i++) { let node = new ListNode(arr[i]); t.next = node; t = t.next; } return res.next; } function quickSort(arr, s, t) { let left = s + 1, right = t, x = arr[s]; while (left <= right) { while (left <= right && arr[left] <= x) left++; while (left <= right && arr[right] >= x) right--; if (left < right) { let t = arr[left]; arr[left] = arr[right]; arr[right] = t; left++; right--; } } if (s != right) { arr[s] = arr[right]; arr[right] = x; } if (s < right - 1) quickSort(arr, s, right - 1); if (t > right + 1) quickSort(arr, right + 1, t); } module.exports = { sortInList: sortInList, };