没在本地测试,一次提交直接通过。
ListNode *removeNthFromEnd(ListNode *head, int n) {
if (head == NULL)
return NULL;
if (head->next == NULL && n == 1)
{
delete head;
return NULL;
}
ListNode *p,*q;
p = q = head;
while(n > 0 && q != NULL)//search the position of q,
{
q = q->next;
n--;
}
if (n > 0)
return head;
if (q == NULL)//delete head
{
ListNode *s = head;
head = head->next;
delete s;
}
else
{
while(q->next)
{
p = p->next;
q = q->next;
}
ListNode *s = p->next;
if (s!=NULL)
{
p->next = s->next;
delete s;
}
}
return head;
}