描述
给你一个链表,删除链表的倒数第 n个结点,并且返回链表的头结点。
进阶:你能尝试使用一趟扫描实现吗?
示例 1:
输入:head = [1,2,3,4,5], n = 2
输出:[1,2,3,5]
示例 2:
输入:head = [1], n = 1
输出:[]
题解
这道题,还是快慢指针,类似滑动窗口一样的效果
/**
* 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 dummyHead = new ListNode(0, head);
let fast = dummyHead,
slow = dummyHead;
for (let i = 0; i <= n; i++) {
fast = fast.next;
}
while (fast) {
slow = slow.next;
fast = fast.next;
}
slow.next = slow.next.next;
return dummyHead.next
};