题解 | #删除链表的倒数第n个节点#
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int k) {
auto dummy = new ListNode(-1); // 虚拟头结点
dummy->next = head; // 虚拟头结点下一个点存下head 1
int n = 0;
for (auto p = dummy; p; p = p->next) n ++ ; // 遍历链表长度
auto p = dummy;
for (int i = 0; i < n - k - 1; i ++ ) p = p->next;
// 删除倒数第n个结点
p->next = p->next->next; // 让结点3的next指针指向5,就可以删除4
return dummy->next;
}
};