题解 | #删除链表的倒数第n个节点#
删除链表的倒数第n个节点
https://www.nowcoder.com/practice/f95dcdafbde44b22a6d741baf71653f6
//快慢指针难点在于while (fast)判断是fast到达最后一个,然后就是slow的起始位置选取,如果都从pHead出发 //则slow会到达倒数k个位置上,无法删除节点,于是new个节点,让slow和fast相距k+1个距离,避免越界 class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param pHead ListNode类 * @param k int整型 * @return ListNode类 */ ListNode* removeNthFromEnd(ListNode* pHead, int k) { ListNode* nHead = new ListNode(-1); nHead->next = pHead; ListNode* slow = nHead; ListNode* fast = pHead; while (k) { fast = fast->next; cout << k << " "; k--; } while (fast) { fast = fast->next; slow = slow->next; } slow->next = slow->next->next; return nHead->next; } };