Skip to content

Instantly share code, notes, and snippets.

@junjiah
Last active August 29, 2015 14:26
Show Gist options
  • Save junjiah/48cc510ddfa1ad7e38ff to your computer and use it in GitHub Desktop.
Save junjiah/48cc510ddfa1ad7e38ff to your computer and use it in GitHub Desktop.
solved 'Remove Nth Node From End of List' on LeetCode https://leetcode.com/problems/remove-nth-node-from-end-of-list/
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
// Very clever algorithm, from
// https://leetcode.com/discuss/21104/simple-java-solution-in-one-pass
// Use a fast runner to pinpoint the right place for deletion in one pass.
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode *fast = head, *slow = head;
for (int i = 0; i < n; ++i) {
fast = fast->next;
}
if (!fast) {
// Delete the head.
ListNode *res = head->next;
delete head;
return res;
}
// Find the right place to delete.
for (fast = fast->next; fast; fast = fast->next, slow = slow->next) ;
delete slow->next;
slow->next = slow->next->next;
return head;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment