力扣题目的链接
思路:可以采用双指针方法实现扫描一边便可以得到结果。
首先通过设置快慢指针,一开始先让快指针先走n步,然后接着让快慢指针一起每次都向前移动一步,知道快指针下一个指向为空指针循环结束。
这样要注意的一点是我们得设置一个虚拟头指针来指向真实的指针,这样我们可以将快慢指针一开始都指向虚拟头指针,注意这里要删除的节点的慢指针指向的下一个。
C++代码:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
if(head == nullptr) return head;
ListNode* dummyHead = new ListNode(0,head);
ListNode* slowPointer = dummyHead, * fastPointer = dummyHead;
while(n > 0 && fastPointer->next != nullptr){
fastPointer = fastPointer->next;
n--;
}
// 防止n太大,没有这个节点,不过我把下面这个判断代码块注释了也是可以通过所有的实例,应该测试没有这个点
if(n > 0 && fastPointer->next == nullptr){
delete dummyHead;
return head;
}
while(fastPointer->next != nullptr){
slowPointer = slowPointer->next;
fastPointer = fastPointer->next;
}
ListNode* tmp = slowPointer->next;
slowPointer->next = slowPointer->next->next;
head = dummyHead->next;
delete dummyHead;
delete tmp;
return head;
}
};
JS代码:
/**
* 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) {
if(head == null) return head;
let dummyHead = new ListNode(0,head);
let fast = dummyHead;
let slow = dummyHead;
while(n > 0 && fast.next != null){
n--;
fast = fast.next;
}
while(fast.next != null){
slow = slow.next;
fast = fast.next;
}
slow.next = slow.next.next;
return dummyHead.next;
};