Skip to content

Instantly share code, notes, and snippets.

@berkayk
Last active January 28, 2016 17:07
Show Gist options
  • Save berkayk/8d8723fbc6b179ccbf9b to your computer and use it in GitHub Desktop.
Save berkayk/8d8723fbc6b179ccbf9b to your computer and use it in GitHub Desktop.
public Node findLastKth(Node head, int k) {
// Assume k > 0
if (k <= 0 || head == null)
return null;
Node current = head;
Node runner = current;
while (k > 0 && runner != null) {
k--;
runner = runner.next;
}
if (runner == null) {
// There aren't enough items in the list
return null;
}
// current is at head
// runner is k step up
while (runner != null) {
runner = runner.next;
current = current.next;
}
return current;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment