题目
给你一个链表,删除链表的倒数第 n 个结点,并且返回链表的头结点。
输入:head = [1,2,3,4,5], n = 2
输出:[1,2,3,5]
思路
双指针中的快慢指针使用,有手就行
代码
/**
* 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* dummyNode = new ListNode(-1);
dummyNode->next = head;
ListNode* fastNode = dummyNode;
ListNode* slowNode = dummyNode;
for(int i=0;i<n+1;i++)
{
fastNode = fastNode->next;
}
while(fastNode != nullptr)
{
fastNode = fastNode->next;
slowNode = slowNode->next;
}
ListNode* delNode = slowNode->next;
slowNode->next = delNode->next;
delete delNode;
ListNode* retNode = dummyNode->next;
delete dummyNode;
return retNode;
}
};