1、双指针明确来说也不算一次遍历因为需要先移动n次快指针
这里要注意删除头节点的情况。
/**
* 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;
for(int i = 0; i < n; i++)
{
fast = fast->next;
}
if(!fast)
{
return head->next;
}
while(fast->next != nullptr)
{
slow = slow->next;
fast = fast->next;
}
slow->next = slow->next->next;
return head;
}
};
2、真正的一次遍历使用递归来做
/**
* 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:
int cur = 0;
ListNode* removeNthFromEnd(ListNode* head, int n) {
if(!head)
{
return nullptr;
}
head->next = removeNthFromEnd(head->next,n);
cur++;
if(cur == n)
{
return head->next;
}
return head;
}
};