题解 | #删除链表的倒数第n个节点#
删除链表的倒数第n个节点
https://www.nowcoder.com/practice/f95dcdafbde44b22a6d741baf71653f6
/** * struct ListNode { * int val; * struct ListNode *next; * }; */ class Solution { public: /** * * @param head ListNode类 * @param n int整型 * @return ListNode类 */ ListNode* removeNthFromEnd(ListNode* head, int n) { // write code here ListNode* dummy = new ListNode(-1); dummy->next = head; ListNode* slow = dummy, *fast = dummy; ListNode* pre = dummy; // 1->2->3 2 // 倒数第几个,就让fast先走几步 while (n > 0) { fast = fast->next; --n; } // fast走到空节点时,slow走到倒数第n个 while (fast != nullptr) { pre = slow; slow = slow->next; fast = fast->next; } pre->next = slow->next; return dummy->next; } };