思路:
先让first指针移动n个节点,只要first->next!=null first&second 同时移动,知道first->next==null 让second->next=second->next->next,就实现删除节点操作
代码:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
auto dummy=new ListNode(-1);
dummy->next=head;
auto first=dummy,second=dummy;
while(n--)
{
first=first->next;
}
while(first->next!=NULL)
{
first=first->next;
second=second->next;
}
second->next=second->next->next;
return dummy->next;
}
};
Every step of barefoot running deserves to be recorded