Skip to content

Instantly share code, notes, and snippets.

@marius92mc
Last active August 29, 2015 14:26
Show Gist options
  • Save marius92mc/d48b691839b0c18e9563 to your computer and use it in GitHub Desktop.
Save marius92mc/d48b691839b0c18e9563 to your computer and use it in GitHub Desktop.
/*
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