leetcode: 19. Remove Nth Node From End of List
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode* dummyHead = new ListNode();
dummyHead->next = head;
ListNode* slow = dummyHead;
ListNode* fast = dummyHead;
for (int i = 0; i < n && fast->next != nullptr; i++)
fast = fast->next;
while (fast->next != nullptr) {
slow = slow->next;
fast = fast->next;
}
slow->next = slow->next->next; // 这一步是精华,注意这个时候只是单纯的删除操作了,和fast指针无关
return dummyHead->next;
}
};