(1)首先,定义fast指针和slow指针,初始值为虚拟头结点
(2)将fast指针向前移动n+1步
(3)slow与fast同时前进,当fast到null时停止
(4)删除slow => next 节点 使slow.next = slow.next.next
代码如下:
/**
* @param {ListNode} head
* @param {number} n
* @return {ListNode}
*/
var removeNthFromEnd = function(head, n) {
let ret = new ListNode(0,head);
let fast = slow = ret;
while(n>=0){
fast = fast.next;
n--;
}
while(fast){
fast = fast.next;
slow = slow.next;
}
slow.next = slow.next.next;
return ret.next;
};