/**
* 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 *dummy = new ListNode(0);
dummy->next = head;
ListNode *fast = dummy->next;
ListNode *slow = dummy;
///**
* 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 *dummy = new ListNode(0);
dummy->next = head;
ListNode *fast = dummy->next;
ListNode *slow = dummy;
//先让快的多走,然后慢的才开始走,之后两个携手一起走,快的到达终点,慢的就是要删除的那个
for(int i = 0;i<=n-1;i++)
{
fast = fast->next;
}
slow = dummy->next;
if(fast==NULL)
{
return head->next;
}
fast = fast->next;// fast再提前走一步,因为需要让slow指向删除节点的上一个节点
while(fast)
{
fast = fast->next;
slow = slow->next;
}
ListNode *temp = slow->next;
slow->next = slow->next->next;
delete temp;
return dummy->next;
}
};
for(int i = 0;i<=n-1;i++)
{
fast = fast->next;
}
slow = dummy->next;
if(fast==NULL)//只有一个节点的情况
{
return head->next;
}
fast = fast->next;// fast再提前走一步,因为需要让slow指向删除节点的上一个节点。
while(fast)
{
fast = fast->next;
slow = slow->next;
}
ListNode *temp = slow->next;//删除掉
slow->next = slow->next->next;
delete temp;
return dummy->next;
}
};
01-04
330
09-07
449