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 == null) return null; let head1 = new ListNode(0); let head2 = head1; let arr = [] while(head){ arr.push(head.val); head = head.next; // console.log(head) } arr.sort((a,b)=>{ return a-b; }) console.log(arr) for(let item of arr){ head1.next = new ListNode(item); head1 = head1.next; } // console.log(head1.next); return head2.next; } module.exports = { sortInList : sortInList };
排序 : 先保存每个节点的数据,然后创建新的链表