Last active
August 29, 2015 14:20
-
-
Save HDegano/3230b50b26f975a08237 to your computer and use it in GitHub Desktop.
Find the Kth to The Last Node of a Singly Link 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
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