Last active
August 29, 2015 14:26
-
-
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/
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) {} | |
* }; | |
*/ | |
// 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