Created
May 30, 2015 18:24
-
-
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.
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 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; | |
} | |
} |
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 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