19. 删除链表的倒数第N个节点
题目
代码
/**
* 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) {
ListNode* slow = head,*fast=head;
for(int i=0;i<n;i++)
{
fast = fast->next;
}
//如果删除的是第一个元素
if(fast==NULL)
{
ListNode* tem = head;
head = head->next;
delete tem;
return head;
}
while(fast->next)
{
fast = fast->next;
slow = slow->next;
}
//最后停止的时候,慢的指针指向的是要删除的点之前那个元素
ListNode* tem = slow->next;
slow->next = slow->next->next;
delete tem;
return head;
}
};
思路
先用一个快指针前进n步,当快指针的下一个是nullptr时,慢指针的下一个则是要删除的元素
https://github.com/li-zheng-hao