19. 删除链表的倒数第 N 个结点 - 力扣(LeetCode)
链表遍历学清楚! | LeetCode:19.删除链表倒数第N个节点_哔哩哔哩_bilibili
普通思想
先遍历一下链表,得到链表个数,知道链表长度,又知道要删除倒数第几个元素,就可以反向推出要删正数第几个元素,去把这个节点删了即可。
虚拟头节点
/**
* 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);
ListNode* cur=head;
dummy->next = head;
int size=0;
while(cur)
{
size++;
cur=cur->next;
}
size-=n;
cur = dummy;
for(int i=0;i<size;i++)
{
cur=cur->next;
}
cur->next=cur->next->next;
return dummy->next;
}
};
双指针法
/**
* 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) {
if(head==NULL)
{
return NULL;
}
ListNode* dummy=new ListNode(0);
dummy->next=head;
head=dummy;
ListNode* slow=head;
ListNode* fast=head;
for(int i=0;i<n;i++)
{
fast=fast->next;
}
while(fast->next!=NULL)
{
fast=fast->next;
slow=slow->next;
}
ListNode* temp=slow->next;
slow->next=slow->next->next;
delete temp;
return dummy->next;
}
};