Last active
August 29, 2015 13:55
-
-
Save sundeepblue/8716674 to your computer and use it in GitHub Desktop.
get last kth node in 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
// 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