Given a linked list and a positive integer k, find the k'th node from the end of the list.

Practice this problem

Iterative Solution

A simple solution is to calculate the total number of nodes n in the linked list first. Then, the k'th node from the end will be (n-k+1)'th node from the beginning.

Following is the C, Java, and Python program that demonstrates it:

C


Download  Run Code

Output:

k’th node from the end is 3

Java


Download  Run Code

Output:

k’th node from the end is 3

Python


Download  Run Code

Output:

k’th node from the end is 3

The above solution does two traversals of the linked list. We can solve this problem in a single list traversal only. The idea is to start from the head node and move a pointer k nodes ahead in the given list. Then, take another pointer starting from the head node and run both pointers in parallel till the first pointer reaches the end of the list. Now, the second pointer will point to the k'th node from the end.

The algorithm can be implemented as follows in C, Java, and Python:

C


Download  Run Code

Output:

k’th node from the end is 3

Java


Download  Run Code

Output:

k’th node from the end is 3

Python


Download  Run Code

Output:

k’th node from the end is 3

The time complexity of the above solution is O(n), where n is the total number of nodes in the linked list, and doesn’t require any extra space.

Recursive Solution

This is a nice problem where the recursive solution code is much cleaner than the iterative code. You probably wouldn’t want to use the recursive version for production code because it will use stack space, which is proportional to the lists’ length.

The recursive implementation can be seen below in C, Java, and Python:

C


Download  Run Code

Output:

k’th node from the end is 3

Java


Download  Run Code

Output:

k’th node from the end is 3

Python


Download  Run Code

Output:

k’th node from the end is 3