Skip to content

Instantly share code, notes, and snippets.

@HDegano
Last active August 29, 2015 14:20
Show Gist options
  • Save HDegano/3230b50b26f975a08237 to your computer and use it in GitHub Desktop.
Save HDegano/3230b50b26f975a08237 to your computer and use it in GitHub Desktop.
Find the Kth to The Last Node of a Singly Link List
public class Solution{
public ListNode FindKthNode(ListNode head, int n){
if(head == null || n <= 0) return null;
ListNode fast = head;
//Verify what is Kth to the last
// 1 -> 2 -> 3 and k = 1, if K = 3 or K = 2. For now assume the former is correct
int stepAhead = n - 1;
for(int i = 0; i < stepAhead; i++){
if(fast.next == null)
return null;
fast = fast.next;
}
ListNode current = head;
while(fast != null){
fast = fast.next;
current = current.next;
}
return current;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment