/** * struct ListNode { * int val; * struct ListNode *next; * }; */ class Solution { public: /** * * @param head ListNode类 * @param n int整型 * @return ListNode类 */ ListNode* removeNthFromEnd(ListNode* head, int n) { // write code here if(head==nullptr) { return nullptr; } ListNode* fake = new ListNode(0); // 伪头节点 fake->next = head; ListNode* fast = fake; ListNode* slow = fake; // 快慢指针 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 fake->next; } };
快慢指针