Today we will write a program for finding the Kth  element from the last.

Code

        public void PrintKthElementFromLast(Node<T> head, int k)
        {
            Node<T> firstPointer = head;
            Node<T> secondPointer = head;
            int counter = 0;
            while (counter < k)
            {
                if (firstPointer == null)
                {
                    Console.WriteLine("LinkList has less number of nodes");
                    return;
                }
                firstPointer = firstPointer.Next;
                counter = counter + 1;
            }
            while (firstPointer != null)
            {
                secondPointer = secondPointer.Next;
                firstPointer = firstPointer.Next;
            }
            Console.WriteLine(string.Format("{0}th Elements from Last is {1} ", k, 
secondPointer.Data)); Console.WriteLine(Environment.NewLine); }

Test Case

1->2->3->4->5->6->

2th Elements from Last is 5


1->2->3->4->5->6->20->17->1->7->

3th Elements from Last is 17


1->2->3->4->5->6->20->17->1->7->

4th Elements from Last is 20


1->2->3->4->5->6->20->17->1->7->

10th Elements from Last is 1