The following function is trying to find the nth to last element of a singly linked list.
For example:
If the elements are
Just another solution to this problem. Though the time complexity remains the same, this code achieves the solution in a single loop.
public Link findKthElementFromEnd(MyLinkedList linkedList, int k)
{
Link current = linkedList.getFirst();//current node
Link currentK = linkedList.getFirst();//node at index k
int counter = 0;
while(current.getNext()!=null)
{
counter++;
if(counter>=k)
{
currentK = currentK.getNext();
}
current = current.getNext();
}
//reached end
return currentK;
}