Remove Nth Node From End of List(C++) 。Given a linked list, remove then-th node from the end of list and return its head.
/**
* 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->next==NULL)
return NULL;
ListNode *prev=head,*cur=head;
for(int i=0;i
cur=cur->next;
if(cur==NULL)
return head->next;
while(cur->next!=NULL)
{
cur=cur->next;
prev=prev->next;
}
prev->next=prev->next->next;
return head;
}
};