双指针,没什么好说的
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
// write code here
if(!head) return head;
ListNode* fast = head;
ListNode* slow = head;
for(int i = 0; i < n && head; ++i) { fast = fast->next; }
if(!fast) return head->next;
while(fast->next) {
fast = fast->next;
slow = slow->next;
}
slow->next = slow->next->next;
return head;
}
};

京公网安备 11010502036488号