Remove Nth Node From End of List
ListNode *removeNthFromEnd(ListNode *head, int n) {
// Note: The Solution object is instantiated only once and is reused by each test case.
if(!head||n<=0)
return NULL;
int i;
ListNode* slow,*fast,*prev=NULL;
slow = fast = head;
for(i=0;i<n-1;i++)
fast = fast->next;
while(fast->next)
{
fast = fast->next;
prev = slow;
slow = slow->next;
}
if(!prev)
{
ListNode* newHead = head->next;
delete head;
return newHead;
}else
{
prev->next = slow->next;
delete slow;
return head;
}
}
浙公网安备 33010602011771号