Skip to content

Instantly share code, notes, and snippets.

@safeng
Last active December 28, 2015 11:59
Show Gist options
  • Save safeng/7497169 to your computer and use it in GitHub Desktop.
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.
/**
* 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