Remove nth Node in List

Problem Statement

Given a linked list, remove the nth node from the end of list and return its head

Solution

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;
}
};
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s