leetcode19.删除链表的倒数第 N 个结点 Posted on 2023-03-02 | In leetcode | Words count in article: 211 | Reading time ≈ 1 给你一个链表,删除链表的倒数第 n 个结点,并且返回链表的头结点。 示例: 12输入:head = [1,2,3,4,5], n = 2输出:[1,2,3,5] 分析: 1快慢指针,快指针先走n,慢指针开始走,当快指针走到尾部时,慢指针走到倒数第n个 代码 C++ 12345678910111213141516171819202122232425262728/** * 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, *slow = head; for (int i = 0;i < n;i ++) fast = fast->next; if (fast == nullptr) return head->next; while (fast->next != nullptr) { slow = slow->next; fast = fast->next; } slow->next = slow->next->next; return head; }}; [原题链接](19. 删除链表的倒数第 N 个结点 - 力扣(Leetcode))