# Find the kth to the last element on a single linked list

• Find the kth to the last element on a single linked list

i.e. if the list is `{ 1, 4, 6, 3, 6, 7 }`

when k = 2, kth to last is 6.

when k = 1, kth to last is 7.

when k = 10000, kth is null, since there aren't that many items on the list

``````public LinkedListImpNode FindKthToLast(int k)
{
int i = 0;
for (; i < k && p != null; i++)
{
p = p.Next;
}
if (p == null && i < k)
{
// the list is too small, we reached the end of the list
// and we did not find k elements, fail here.
return null;
}

//move the pointer to the end, sk moves with it
while (p != null)
{
p = p.Next;
kNode = kNode.Next;
}
return kNode;
}
``````

Here is a testcase

``````[TestMethod]
public void FindKthTests()
{
// build the list  {1, 4, 6, 3, 6, 7}

Assert.AreEqual(1, list.FindKthToLast(6).Value);
Assert.AreEqual(3, list.FindKthToLast(3).Value);
Assert.AreEqual(6, list.FindKthToLast(2).Value);
Assert.AreEqual(7, list.FindKthToLast(1).Value);
Assert.IsNull(list.FindKthToLast(7));
}``````

• `````` private static int FindKth(ListNode head, int k)
{
//null check
if (head == null || k < 1)
return -1;

int i = 1;
{
// not enough nodes
if (head.next == null && i < k)
return -1;
else
{
if (i == k && head.next == null)
{
return val.val;
}
else
{
if (i == k)
val = val.next;
else
i++;
}