删除倒数第n个节点
因为需要知道倒数第n个节点的前一个节点
所以需要知道全部的链表节点数量
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
int i=1;
ListNode *p=head;
while(head->next=NULL){
i++;
}
if(i==n){
head=head->next;
return head;
}else{
for(int m=1;m<i-n;m++)
{
p=p->next;
}
p->next=p->next->next;
}
return head;
}
};
但是出错了。。。
改进——>
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
int i=0;
ListNode *p=head;
while(p)
{
i++;
p=p->next;
}
p=head;
if(i==1) return {};
else if(i-n==0) return head->next;
else
{
for(int m=1;m<i-n;m++)
{
p->next;
}
p->next=p->next->next;
}
return head;
}
};