19. 删除链表的倒数第 N 个结点
- 设置虚拟头结点dummy
- 遍历到链表末尾,而不是null(末尾下一个
ListNode* removeNthFromEnd(ListNode* head, int n) {
auto dummy = new ListNode(-1);
dummy->next = head;
auto fast = dummy,slow = dummy;
while(n) n--,fast=fast->next;
while(fast->next){
slow = slow->next;
fast = fast->next;
}
slow->next = slow->next->next;
return dummy->next;
}
237. 删除链表中的节点
void deleteNode(ListNode* node) {
node->val=node->next->val;
node->next=node->next->next;
}