删除链表的倒数第N个节点

首先计算链表的长度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
/**
* 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 length = 0;
let cur = head;
// 计算length
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;
};


本站由 ao 使用 Stellar 1.29.1 主题创建。
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议,转载请注明出处。