1. /**
    2. * Definition for singly-linked list.
    3. * function ListNode(val, next) {
    4. * this.val = (val===undefined ? 0 : val)
    5. * this.next = (next===undefined ? null : next)
    6. * }
    7. */
    8. /**
    9. * @param {ListNode} head
    10. * @param {number} n
    11. * @return {ListNode}
    12. */
    13. var removeNthFromEnd = function(head, n) {
    14. const stack = []
    15. let cur = head
    16. while (cur) {
    17. stack.push(cur)
    18. cur = cur.next
    19. }
    20. const length = stack.length,
    21. pre = stack[length - n - 1] || null,
    22. target = stack[length - n]
    23. if (!length || length < n) {
    24. return null
    25. }
    26. if (pre === null) {
    27. head = head.next
    28. } else {
    29. pre.next = target.next
    30. }
    31. return head
    32. };
    1. /**
    2. * Definition for singly-linked list.
    3. * function ListNode(val, next) {
    4. * this.val = (val===undefined ? 0 : val)
    5. * this.next = (next===undefined ? null : next)
    6. * }
    7. */
    8. /**
    9. * @param {ListNode} head
    10. * @param {number} n
    11. * @return {ListNode}
    12. */
    13. var removeNthFromEnd = function (head, n) {
    14. let curi = head,
    15. curj = head
    16. while (n > 0) {
    17. curj = curj.next
    18. n--
    19. }
    20. if(!curj) {
    21. head = head.next
    22. return head
    23. }
    24. while (curj.next) {
    25. curj = curj.next
    26. curi = curi.next
    27. }
    28. curi.next = curi.next.next
    29. return head
    30. };