DRAW A PICTURE AND Use two pointers.
it is easy to solve
/**
* 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)
return NULL;
ListNode *pre;
ListNode *tail;
pre = head;
tail = head;
for(int i = 0;i<n;i++)
{
tail = tail->next;
}
if(tail == NULL)
return head->next;
while(tail->next!= NULL)
{
tail= tail->next;
pre = pre->next;
}
ListNode * temp = pre->next;
pre->next = temp->next;
return head;
}
};