给你一个链表,删除链表的倒数第 n
个结点,并且返回链表的头结点
因为题目是删除倒数第n个节点,要求指向第n-1个节点,故设置虚拟头结点,本题利用双指针法,先让快指针移动n+1步,再同时移动快慢指针,直到快指针指向空为止。
/**
* 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) {
ListNode *dum=new ListNode(0);
dum ->next=head;
ListNode *slow=dum;
ListNode *fast=dum;
while(n&&fast !=NULL){
n--;
fast=fast->next;
}
fast=fast->next;
while(fast !=NULL){
fast=fast->next;
slow=slow->next;
}
slow->next=slow->next->next;
return dum->next;
}
};