Find the kth to last element of a singly linked list
Any comments?
import org.junit.Test;
public class Solution {
// Find kth to last element of a singly linked list
// Solution proposed: Use a runner that is k steps ahead
// when runner hits end of linked list, slow on kth to end element
public Node n3 = new Node(3);
public Node n2 = new Node(2,n3);
public Node n1 = new Node(1,n2);
public Node head = new Node(0,n1);
public Node findKthToLast(Node head, int k){
// place the runner k steps ahead
if (head == null){
return null;
}
Node runner = new Node(head);
Node slow = new Node(head);
for (int i = 0; i < k; i++){
if (runner.getNext() == null){
return null;
}
else{
runner = runner.getNext();
}
}
while (runner != null){
runner = runner.getNext();
slow = slow.getNext();
}
return slow;
}
@Test
void test1th(){
System.out.println(findKthToLast(head, 1).getValue());
}
@Test
void testLargerThanList(){
System.out.println(findKthToLast(head, 15));
}
@Test
void testNonDegenerate(){
System.out.println(findKthToLast(head, 2).getValue());
}
public static void main(String[] args) {
Solution e = new Solution();
e.test1th();
e.testLargerThanList();
e.testNonDegenerate();
}
}
class Node {
private int value;
private Node next;
public Node(int v) {
value = v;
}
public Node(int v, Node n) {
value = v;
next = n;
}
public Node(Node n){
this.value = n.value;
this.next = n.next;
}
public Node getNext(){
return next;
}
public int getValue(){
return value;
}
public void setNext(Node n){
this.next = n;
}
}