首先计算链表的长度length,然后length-n-1就是要迭代的次数,定位到要删除的节点的前一个节点
边界情况有两种:
- length-n-1 === 0
- length-n-1 === -1
对这两种情况做出解释:
- === 0,要删除第二个节点
- === -1,要删除头节点
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
|
var removeNthFromEnd = function (head, n) { let length = 0; let cur = head; while (cur) { length++; cur = cur.next; } let target = length - n - 1; cur = head; while (target > 0) { cur = cur.next; target--; } if (target === 0) { if (cur.next && cur.next.next) { cur.next = cur.next.next; } else { cur.next = null; } } else if (target === -1) { head = head.next; } else if (cur.next) { cur.next = cur.next.next; } return head; };
|