19. 删除链表的倒数第 N 个结点
最近更新:2025-03-25 | 字数总计:100 | 阅读估时:1分钟 | 阅读量:次
- 解析
- 双指针+哑节点
Problem: 19. 删除链表的倒数第 N 个结点
解析
双指针+哑节点
简单的一批(先不做内存管理啦)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| class Solution { public: ListNode *removeNthFromEnd(ListNode *head, int n) { if (head->next == nullptr) { return nullptr; } ListNode *dummy = new ListNode(); dummy->next = head; ListNode *slow = dummy; ListNode *fast = dummy; for (int i = 0; i <= n; ++i) { fast = fast->next; } while (fast != nullptr) { fast = fast->next; slow = slow->next; } slow->next = slow->next->next; return dummy->next; } };
|