题目链接:https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list/
题目如下:
/**
* 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* dummyHead=new ListNode(-1);//头节点可能发生改变
dummyHead->next=head;
ListNode *slow=dummyHead,*fast=dummyHead;
for(int i=0;i<n+1;i++)//fast先走n+1步,因为只有这样同时移动时slow才能指向删除节点的上一个节点(方便做删除操作)
fast=fast->next;
while(fast!=NULL){
fast=fast->next;
slow=slow->next;
}
slow->next=slow->next->next;
return dummyHead->next;
}
};