class Solution { public: ListNode* removeNthFromEnd(ListNode* head, int n) { ListNode* slow head; ListNode* fast head; // 1. fast 先走 n 步 while (n-- fast ! nullptr) { fast fast-next; } // 2. 如果 fast 为空说明要删除的是头节点 if (fast nullptr) { return head-next; } // 3. 同时移动直到 fast 到达最后一个节点 while (fast-next ! nullptr) { fast fast-next; slow slow-next; } // 4. 删除 slow 的下一个节点 slow-next slow-next-next; return head; } };class Solution { public: ListNode* removeNthFromEnd(ListNode* head, int n) { ListNode dummy(0, head); // 哑节点简化边界处理 ListNode* slow dummy; ListNode* fast dummy; // fast 先走 n1 步 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; } };
LeetCodehot100-19删除链表的倒数第 N 个结点
class Solution { public: ListNode* removeNthFromEnd(ListNode* head, int n) { ListNode* slow head; ListNode* fast head; // 1. fast 先走 n 步 while (n-- fast ! nullptr) { fast fast-next; } // 2. 如果 fast 为空说明要删除的是头节点 if (fast nullptr) { return head-next; } // 3. 同时移动直到 fast 到达最后一个节点 while (fast-next ! nullptr) { fast fast-next; slow slow-next; } // 4. 删除 slow 的下一个节点 slow-next slow-next-next; return head; } };class Solution { public: ListNode* removeNthFromEnd(ListNode* head, int n) { ListNode dummy(0, head); // 哑节点简化边界处理 ListNode* slow dummy; ListNode* fast dummy; // fast 先走 n1 步 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; } };