/**
* 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* Newhead = head;
ListNode* p=head;
if(head==NULL) return NULL;
for(int i =0;i<n;i++)
{
Newhead=Newhead->next;
}
if(Newhead==NULL)
return head->next;
while(Newhead->next!=NULL)
{
Newhead=Newhead->next;
p = p->next;
}
p ->next= p->next->next;
return head;
}
};
易错点:
- 头结点head直接是第一个结点的地址,而不是head->next为第一个结点,head->next指向的是第二个结点。
- 删除p结点的下一个结点是p->next=p->next->next,而删除p结点无法直接用p=p->next,p=p->next为指针后移操作,没有删除结点。