# 题目描述
给定一个链表,删除链表的倒数第 n 个结点,并且返回链表的头结点。
提示:
- 链表中结点的数目为 sz
1 <= sz <= 30
0 <= Node.val <= 100
1 <= n <= sz
# 测试用例
- 输入:
head = [1,2,3,4,5], n = 2
- 输出:
[1,2,3,5]
# 代码实现
/**
* 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 dmy = new ListNode(-1, head);
let fast = dmy;
let slow = dmy;
while(n){
fast = fast.next;
n --;
}
while(fast && fast.next){
fast = fast.next;
slow = slow.next;
}
slow.next = slow.next.next;
return dmy.next;
};
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
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