Return Kth to Last: Implement an algorithm to find the kth to last element of a singly linked list Implement an algorithm to find the kth to last element of a singly linked list.


Any comments or feedback regarding this?

I came up with another algorithm that uses HashMap to find the kth to the last element in a LinkedList.

public static int getKthToLastElement(LinkedListNode head, int k){
    LinkedListNode n = head;

    if(head == null || k &lt; 0)
        return -1;

    int index = 0;
    HashMap&lt;Integer,Integer&gt; map = new HashMap&lt;Integer, Integer&gt;();
    while (n != null){
        map.put(index,n.data);
        index++;
        n = n.next;
    }

    if(k &gt; map.size() -1){
        return  -1;
    }
    return map.get(map.size() - 1 - k);
}
Your if(head == null || k &lt; 0) special case is unnecessary, since it is covered by the if(k &gt; map.size() -1) test.  You should also never omit the "optional" braces for a multi-line block.

Actually, the if(k &gt; map.size() -1) test could also be eliminated, if you used Map.getOrDefault(…, -1).

The loop would be more easily recognized if written as a for loop.

public static int getKthToLastElement(LinkedListNode head, int k) {
    int index = 0;
    Map&lt;&gt; map = new HashMap&lt;Integer, Integer&gt;();
    for (LinkedListNode n = head; n != null; n = n.next) {
        map.put(index++, n.data);
    }
    return map.getOrDefault(map.size() - 1 - k, -1);
}


I think that converting the linked list to an ArrayList would be better than converting it to a HashMap.  You would then be converting a cumbersome linked list into a kind of list that is useful and idiomatic in Java.