快慢指针加虚拟头结点处理。注意处理链表长度为n的和小于n的情形。
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode node(0);
node.next = head;
ListNode* fast = head;
ListNode* slow = &node;
// fast前进 n步
for(int i=0; i<n; i++) {
if(!fast) return head;
fast = fast->next;
}
while(fast) {
fast = fast->next;
slow = slow->next;
}
ListNode* temp = slow->next->next;
delete slow->next;
slow->next = temp;
return node.next;
}
}; 
京公网安备 11010502036488号