题解 | #删除链表的倒数第n个节点#
删除链表的倒数第n个节点
https://www.nowcoder.com/practice/f95dcdafbde44b22a6d741baf71653f6
/** * struct ListNode { * int val; * struct ListNode *next; * }; */ #include <cstddef> #include <list> class Solution { public: /** * * @param head ListNode类 * @param n int整型 * @return ListNode类 */ ListNode* removeNthFromEnd(ListNode* head, int n) { // write code here ListNode* virhead = new ListNode(-1); virhead->next = head; //这里将fast指向虚拟头结点的下一个,是为了方便后面得到删除元素的前驱 //你将下面while改为 while(fast != nullptr && pos != n+1)是一样的效果 ListNode* fast = virhead->next; ListNode* slow = virhead; size_t pos = 0; while(fast != nullptr && pos != n) { ++pos; fast = fast->next; } //保证n的正确 if(pos != n) return nullptr; while(fast != nullptr) { slow = slow->next; fast = fast->next; } ListNode* del = slow->next; slow->next = slow->next->next; delete del; del = virhead->next; //销毁分配的内存 delete virhead; return del; } };