哨兵节点主要是用来避免单独处理删除头节点的情况。
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode *dummy = new ListNode(0, head); //使用哨兵节点(虚拟头节点)
ListNode *fast = head, *slow = dummy; //慢指针起始位置在快指针前面
while (n -- ) fast = fast->next; //快指针先走n步
while (fast)
{
fast = fast->next; //快慢指针齐步走,直到快指针走完链表
slow = slow->next;
}
slow->next = slow->next->next; //慢指针跳过下一节点,即倒数第n个节点
return dummy->next;
}
};