视频讲解
[bilibili cid=”” page=”1″]840006760[/bilibili]
代码
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* removeNthFromEnd(ListNode* head, int n) { ListNode dummy(0); ListNode* tail = &dummy; tail->next = head; ListNode* fast = &dummy; ListNode* slow = &dummy; for (int i = 0; i < n; i++) { fast = fast->next; } while (fast->next != nullptr) { fast = fast->next; slow = slow->next; } slow->next = slow->next->next; return dummy.next; } };