/**
* 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 * first=head ,*second = head;
if(head == NULL || head == NULL) return NULL;
for(int i=0;i<n;i++)
first = first->next;
if(first == NULL)
return head->next;
while(first->next){
first = first->next;
second = second->next;
}
second->next = second->next->next;
return head;
}
};
這道題就是採用雙指針,兩個指針之間差N個,second是第倒數N+1個指針,並且要注意到刪除頭節點的情況。