1. 题目描述
给你一个链表,删除链表的倒数第 n 个结点,并且返回链表的头结点。
示例 1:
输入:head = [1,2,3,4,5], n = 2
输出:[1,2,3,5]
示例 2:
输入:head = [1], n = 1
输出:[]
示例 3:
输入:head = [1,2], n = 1
输出:[1]
2. 解题思路
首先定义快指针fast和慢指针slow,先让快指针向前走n+1步,然后再同时移动快慢指针,当快指针指向null的时候,slow->next指向slow->next->next
3. 代码实现
class Solution {
public:ListNode* removeNthFromEnd(ListNode* head, int n) {ListNode* dummy = new ListNode(0);dummy->next = head;ListNode* slow = dummy;ListNode* fast = dummy;while(n+1){fast = fast->next;n--;}// fast = fast->next;while(fast != nullptr){slow = slow->next;fast = fast->next;}slow->next = slow->next->next;return dummy->next;}
};