题解 | #删除链表的倒数第n个节点#
删除链表的倒数第n个节点
https://www.nowcoder.com/practice/f95dcdafbde44b22a6d741baf71653f6
快慢指针思路
快指针抢跑n个节点
class Solution {
public:
/**
*
* @param head ListNode类
* @param n int整型
* @return ListNode类
*/
ListNode* removeNthFromEnd(ListNode* head, int n) {
// write code here
ListNode* newList = new ListNode(-1);
newList->next = head;
ListNode* cur = head;
ListNode* pre = newList;
ListNode* fast = head;
while(n--){
fast = fast->next;
}
while(fast){
fast = fast->next;
pre = cur;
cur = cur->next;
}
pre->next = cur->next;
return newList->next;
}
};