/**
* 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(n<1 || head==nullptr)
return nullptr;
int length=0;
ListNode* p=head;
ListNode* p1,*p2;
p1=p2=head;
int i;
for(i=n;i>0 && p1->next!=nullptr;--i){
p1=p1->next;
}
if(i>0){
ListNode* newHead=head->next;
delete head;
return newHead;
}
while(p1->next!=nullptr){
p1=p1->next;
p2=p2->next;
}
ListNode* nodeTobeDeleted=p2->next;
p2->next=p2->next->next;
delete nodeTobeDeleted;
return head;
}
};