class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
if (head->next == NULL)
return NULL;
ListNode *p = head;
int i = 0;
while (p != NULL) //获得链表总共有的元素个数
{
i++;
p = p->next;
}
int j = 0;
p = head;//经过上个循环,p已经改变,所以要重新赋值
while (p != NULL)
{
j++;
if (j == i - n)
{
p->next = p->next->next;
return head;
}
p = p->next;
}
head=head->next;//当i-n=0的时候,即要删除第一个数
return head;
}
};
转载于:https://my.oschina.net/a20092173/blog/511363