Skip to content

Instantly share code, notes, and snippets.

@mogutou1214
Created May 30, 2015 18:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mogutou1214/8c3d5871ea1a7da4d234 to your computer and use it in GitHub Desktop.
Save mogutou1214/8c3d5871ea1a7da4d234 to your computer and use it in GitHub Desktop.
CC2.2 - Implement an algorithm to find the kth to last element of a singly linked list.
public class findKth {
public static LinkedListNode solution(LinkedListNode head, int Kth) {
if (Kth < 0) return null;
if (head == null) return null;
LinkedListNode walker = head;
LinkedListNode runner = head;
for (int i = 0; i < Kth-1; i++) {
if (runner == null) return null;
runner = runner.next;
}
while (runner.next != null) {
walker = walker.next;
runner = runner.next;
}
return walker;
}
}
public class findKth {
public static LinkedListNode solution(LinkedListNode head, int Kth) {
if (Kth < 0) return null;
if (head == null) return null;
LinkedListNode walker = head;
LinkedListNode runner = head;
for (int i = 0; i < Kth-1; i++) {
if (runner == null) return null;
runner = runner.next;
}
while (runner.next != null) {
walker = walker.next;
runner = runner.next;
}
return walker;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment