题目描述:给你一个链表,删除链表的倒数第 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-1;i++)
{
fast = fast->next;
}
if(fast->next == NULL)
{
return head->next;
}
fast = fast->next;
while(fast->next!=NULL)
{
fast = fast->next;
slow = slow->next;
}
slow->next = slow->next->next;
return head;
}
};