Last active
December 28, 2015 11:59
-
-
Save safeng/7497169 to your computer and use it in GitHub Desktop.
Remove Nth Node From End of List.
Given a linked list, remove the nth node from the end of list and return its head.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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 == NULL) | |
return NULL; | |
ListNode guard(0); | |
guard.next = head; | |
// find the n-1th node from the end | |
ListNode * p = &guard; | |
ListNode * pp = &guard; | |
for(int i = 0; i<n; ++i) | |
{ | |
pp = pp->next; | |
if(pp == NULL) | |
return head; | |
} | |
while(pp->next) | |
{ | |
pp = pp->next; | |
p = p->next; | |
} | |
// remove p->next | |
ListNode * temp = p->next; | |
p->next = temp->next; | |
delete temp; | |
return guard.next; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment