一、需求分析
需求:一次遍历并完成指定节点的删除
二、解决方法
目标
(1):找到指定节点,并只用一次遍历
解决:利用slow fast 指针之间距离进行定位
(2):处理特殊输入
解决:在最开始进行条件判断,空则返回NULL
个人代码
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode*fast=head;
ListNode*slow=head;
int reamark=0;
//解决空返回问题
if(!head||!head->next)return NULL;
while(reamark!=n){
fast=fast->next;
++reamark;
}
if(!fast){
return head->next;
}
while(fast->next){
slow=slow->next;
fast=fast->next;
}
slow->next=slow->next->next;
return head;
}
};