/** * Definition for singly-linked list. * function ListNode(val) { * this.val = val; * this.next = null; * } */ /** * @param {ListNode}head * @param {number}val * @return {ListNode} */ var removeElements = function(head, val) { if (!head) { return head } let array = listNodeToArray(head) array = array.filter(i => (i !== val)) return arrayToListNode(array) };
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 }