添加头结点,防止删除的是第一个节点
要指向删除节点的前一个节点
class Solution {
public:
ListNode *removeNthFromEnd(ListNode *head, int n) {
if(!head||n<1)return NULL;
ListNode*dummy=new ListNode(-1);
dummy->next=head;
ListNode*p=dummy;
while(p&&n)n--,p=p->next;
if(n)return head;
ListNode*pre=dummy;
while(p&&p->next)pre=pre->next,p=p->next;
ListNode*pnext=pre->next;
pre->next=pnext->next;
delete pnext;
return dummy->next;
}
};