Remove Nth Node From End of List
PROBLEM :
Given a linked list, remove the nth node from the end of list and return its head.
For example,
Given linked list: 1->2->3->4->5, and n = 2.
After removing the second node from the end, the linked list becomes 1->2->3->5.
Note:
Given n will always be valid.
Try to do this in one pass.
--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :
--------------------------------------------------------------------------------
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* removeNthFromEnd(struct ListNode* head, int n) {
struct ListNode *n1,*n2,*temp ;
int i=1 ;
n1=head ;
n2=head ;
while(i!=n)
{
n1=n1->next ;
i++ ;
}
if(n1->next==NULL)
{
temp=head ;
head=head->next ;
free(temp) ;
return head ;
}
i=1 ;
n1=head ;
n2=head->next ;
while(i<n&&i!=n)
{
n2=n2->next ;
i++ ;
}
while(n2->next!=NULL)
{
n1=n1->next ;
n2=n2->next ;
}
temp=n1->next ;
n1->next=temp->next ;
free(temp) ;
return head ;
}
---------------------------------------------------------------------------------
Given a linked list, remove the nth node from the end of list and return its head.
For example,
Given linked list: 1->2->3->4->5, and n = 2.
After removing the second node from the end, the linked list becomes 1->2->3->5.
Note:
Given n will always be valid.
Try to do this in one pass.
--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :
--------------------------------------------------------------------------------
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* removeNthFromEnd(struct ListNode* head, int n) {
struct ListNode *n1,*n2,*temp ;
int i=1 ;
n1=head ;
n2=head ;
while(i!=n)
{
n1=n1->next ;
i++ ;
}
if(n1->next==NULL)
{
temp=head ;
head=head->next ;
free(temp) ;
return head ;
}
i=1 ;
n1=head ;
n2=head->next ;
while(i<n&&i!=n)
{
n2=n2->next ;
i++ ;
}
while(n2->next!=NULL)
{
n1=n1->next ;
n2=n2->next ;
}
temp=n1->next ;
n1->next=temp->next ;
free(temp) ;
return head ;
}
---------------------------------------------------------------------------------
Comments
Post a Comment