题解 | #删除链表的倒数第n个节点#
删除链表的倒数第n个节点
https://www.nowcoder.com/practice/f95dcdafbde44b22a6d741baf71653f6
使用虚拟头节点去删除
slow->next=slow->next->next;
fast到达第n个节点还需要再到下一步,使得slow指向需要删除节点的上一个节点
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
class Solution {
public:
/**
*
* @param head ListNode类
* @param n int整型
* @return ListNode类
*/
ListNode* removeNthFromEnd(ListNode* head, int n) {
// write code here
if(head==nullptr || n==0){
return head;
}
ListNode* vh=new ListNode(0);
vh->next=head;
ListNode* fast=vh , *slow=vh;
for(int i=0; i< n; i++){
fast=fast->next;
if(fast==nullptr){//如果越界
return head;
}
}
fast=fast->next;
while(fast!=nullptr){
fast=fast->next;
slow=slow->next;
}
slow->next=slow->next->next;
return vh->next;
}
};

