定义两个都指向首节点的指针,第一个指针先移动n次,然后第二个指针移动与第一个指针一起移动,当第一个指针移动到末尾指针的时候,第二个指针刚好移动到倒数第n+1个节点,此时修改指针指向完成删除。
class Solution {
public:
ListNode* remove(ListNode* head, int n) {
if(head==nullptr || head->next==nullptr)
return nullptr;
ListNode* first = head;
ListNode* second = head;
for(int i=0;i<n;++i){
first = first->next;
if(first->next==nullptr && i<n-1)
return second->next;
}
while(first->next!=nullptr){
first = first->next;
second = second->next;
}
if(second->next)
second->next = second->next->next;
return head;
}
};