/** * Definition for singly-linked list. * function ListNode(val, next) { * this.val = (val===undefined ? 0 : val) * this.next = (next===undefined ? null : next) * } *//** * @param {ListNode} head * @param {number} n * @return {ListNode} */var removeNthFromEnd = function(head, n) { const stack = [] let cur = head while (cur) { stack.push(cur) cur = cur.next } const length = stack.length, pre = stack[length - n - 1] || null, target = stack[length - n] if (!length || length < n) { return null } if (pre === null) { head = head.next } else { pre.next = target.next } return head};
/** * Definition for singly-linked list. * function ListNode(val, next) { * this.val = (val===undefined ? 0 : val) * this.next = (next===undefined ? null : next) * } *//** * @param {ListNode} head * @param {number} n * @return {ListNode} */var removeNthFromEnd = function (head, n) { let curi = head, curj = head while (n > 0) { curj = curj.next n-- } if(!curj) { head = head.next return head } while (curj.next) { curj = curj.next curi = curi.next } curi.next = curi.next.next return head};