/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) : val(x), next(nullptr) {}
* };
*/
#include <cstddef>
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param head ListNode类
* @param n int整型
* @return ListNode类
*/
ListNode* removeNthFromEnd(ListNode* head, int n) {
// write code here
//为空直接返回
if(head == NULL) return head;
//来一个新表头防止第一个节点被删后没有返回值
ListNode *mxy = new ListNode(0);
mxy->next = head;
head = mxy;
//快慢指针
ListNode *fast = head;
ListNode *slow = head;
//快指针定好长度
for(int i = 0; i < n; i++){
fast = fast->next;
}
//快慢指针同步移动,slow指针定位所需要删除的节点
while(fast->next != NULL){
slow = slow->next;
fast = fast->next;
}
//常规删除 一跨连二跨
ListNode *temp = slow->next;
slow->next = slow->next->next;
delete temp;
return mxy->next;
}
};