Problem Statement
Given a linked list, remove the nth node from the end of list and return its head
Solution
[sourcecode language="cpp"]
class Solution {
public:
ListNode *removeNthFromEnd(ListNode *head, int n) {
int cnt = 1;
ListNode *nth = head,*nth_prev = NULL, *rider = head;
if(head == NULL)
return NULL;
while( rider != NULL )
{
if( cnt > n)
{
nth_prev = nth;
nth = nth->next;
}
cnt++;
rider = rider->next;
}
if( nth_prev == NULL ) //This is head
{
return nth->next;
}
nth_prev->next = nth->next;
delete nth;
return head;
}
};
[/sourcecode]
No comments:
Post a Comment