K-th element from the end of a list

Linked list is a linear data structure. Different nodes are added as a chained manner in a list. A singly linked list is a list having pointer to the next item in the list. Every node in a singly linked list have two properties: a data part and a pointer to the next node. Head of a linked list denoting the first node in a linked list.

Problem Statement

Here the input will be an integer value position and the list reference which points to the head of the linked list. We need to find out the Kth element in the linked list from the end of the linked list. Last element of the linked list will be the first element from the end.

Algorithm

Step 1. Define two pointers first and second

Step 2. Let both the pointer points to the head

Step 3. Iterate through the list, till the Kth element from the head and increment the first pointer. Now first pointer points to Kth element and second pointer points to the head.

Step 4. Till first points to the last element in the list iterate through the list and increment both the first and second pointers.

Step 5. Return the second

Java Code

int insertFromEnd (LinkedListNode head, int position){

LinkedListNode first = head;

LinkedListNode = second;

int currentPosition = 0;

while(currentPosition<=position){

first = first.next;

currentPosition++;

}

while(first.next != null){

first = first.next;

second = second.next;

}

return second.data;

}