/**
* 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) {
if(head == NULL || head->next == NULL){
return NULL;
}
ListNode* p1 = head;
ListNode* p2 = head;
int flag = 0;
while(flag++ < n-1){
p2 = p2->next;
}
ListNode* pt = NULL;
while(p2->next != NULL){
pt = p1;
p1 = p1->next;
p2 = p2->next;
}
if(p1 == head){
return head->next;
}
else{
pt->next = p1->next;
}
return head;
}
};
把边界条件考虑清楚。