Last active
August 29, 2015 14:26
-
-
Save marius92mc/d48b691839b0c18e9563 to your computer and use it in GitHub Desktop.
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
/* | |
struct ListNode { | |
int val; | |
ListNode* next; | |
}; | |
*/ | |
/** | |
* return the nth node from the end of the list | |
* in O(N) time, O(1) space | |
*/ | |
ListNode* getCorrespondingNode(ListNode* head, int n) { | |
ListNode* a = head; | |
ListNode* b = head; | |
// make with first pointer n steps | |
for (int i = 0; i < n; i++) { | |
if (a != NULL) { | |
a = a->next; | |
} | |
} | |
/** | |
* after that, continue with the same speed with both pointers | |
* and when the first pointer reaches the end of the list, | |
* then the second pointer represents the Nth node | |
* from the end of the list | |
*/ | |
while (a != NULL && b != NULL) { | |
a = a->next; | |
b = b->next; | |
} | |
return b; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment