functionlistNodeToArray (head) { let array = [] while (head) { array.push(head.val) head = head.next } return array }
functionarrayToListNode(array) { if(!array || !array.length) { returnnull } let node let head = new ListNode(array[0]) let pnode = head //pnode变量用来保存前一个节点 for(let i = 1; i < array.length; i++) { node = new ListNode(array[i]) pnode.next = node //将前一个节点的next指向当前节点 pnode = node //将node赋值给pnode } return head }