Skip to content

Instantly share code, notes, and snippets.

@sundeepblue
Last active August 29, 2015 13:55
Show Gist options
  • Save sundeepblue/8716674 to your computer and use it in GitHub Desktop.
Save sundeepblue/8716674 to your computer and use it in GitHub Desktop.
get last kth node in list
// key idea: first, go k-1 step.
ListNode* get_last_kth_node(ListNode *head, int k) {
if(!head) return NULL;
if(k == 0) return NULL;
ListNode *p = head;
// run k-1 steps
for(int i=0; i<k-1; i++) {
if(p->next == NULL) return NULL;
p = p->next;
}
ListNode *slow = head;
while(p->next) {
slow = slow->next;
p = p->next;
}
return slow;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment