class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode* p=head;
ListNode *q =head;
int cnt=0;
if(n==1){
if(p->next==nullptr){
return nullptr;
}else{
while(p->next->next){
p=p->next;
}
q=p;
q->next=nullptr;
return head;
}
}else{
while(p->next){
cnt++;
p=p->next;
if(cnt>n){
q=q->next;
}
}
if(cnt==n-1){
ListNode* r=head->next;
return r;
}else{
ListNode* R=q->next;
q->next=R->next;
return head;
}
}
}
};
此博客展示了一段C++代码,定义了一个Solution类,其中的removeNthFromEnd函数用于移除链表中倒数第N个节点。代码针对不同情况进行了逻辑处理,如N为1和不为1的情况,最终返回处理后的链表头节点。

被折叠的 条评论
为什么被折叠?



