题解 | #单链表的排序#
单链表的排序
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 if(!head || !head.next){ return head } const array = []; let cur = head; while(cur){ const temp = cur; cur = cur.next; temp.next = null array.push(temp) } array.sort((a,b)=>(a.val-b.val)); for(let i=0;i<array.length-1;i++){ array[i].next = array[i+1]; } return array[0] } module.exports = { sortInList : sortInList };
解题思路:用array存放节点,然后通过array排序,最后重新组装
#单链表的排序#