class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode *temp=head;
int count=0;
while(temp)
{
count++;
temp=temp->next;
}
int del=count-n+1;
ListNode *prenode=new ListNode(-1);
ListNode *pre=prenode;
pre->next=head;
temp=head;
count=1;
while(temp) {
if (count == del) {
pre->next = pre->next->next;
break;
}
pre=temp;
temp=temp->next;
count++;
}
return prenode->next;
}
};
这是第二种解决方法 整个过程只需要遍历一遍 当后指针指向n+2个节点的时候 前指针指向第一个数 当后指针为null的时候 前指针指向倒数第n个节点的前驱节点。
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
if(!head)
return head;
ListNode *prehead=new ListNode(-1);
if(!head->next&&n==1)
return NULL;
prehead->next=head;
ListNode *first=NULL;
ListNode *tail=prehead;
int count=1;
while(tail)
{
if(count==n+2)
{
first=prehead;
}
tail=tail->next;
count++;
if(first)
first=first->next;
}
if(count==n+2)
{
first=prehead;
}
first->next=first->next->next;
return prehead->next;
}
};