/**
* 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个指针,并且要注意到删除头节点的情况。