题目地址: https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list/
题目描述: 给你一个链表,删除链表的倒数第 n 个结点,并且返回链表的头结点。
参考代码:
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode* visualH = new ListNode();
visualH->next = head;
ListNode* fast = visualH;
ListNode* slow = visualH;
while (n-- && fast) {
fast = fast->next;
}
if (fast == nullptr) {
return head;
}
while (fast->next) { // 查询删除节点的上个节点
fast = fast->next;
slow = slow->next;
}
ListNode *tmp = slow->next;
slow->next = slow->next->next;
delete tmp;
return visualH->next;
}
};