Company-Specific Courses
Free Resources

Edit

Edit

# Program to return nth node from the end of a linked list | FACE Prep

Published on 10 Mar 2020

Program to find the nth node from the end of a linked list is discussed here. Given a linked list, the task is to find the Nth node from the end of the list and return it.

This problem can be solved in two different ways.

Method 1: By finding the length of the linked list, the Nth node from the end can be found easily.

Method 2: By using two pointers, the Nth node from the end can be found.

For example, consider the linked list given below.

Linked List : 1 -> 2 -> 3 -> 4 -> 5

4th node from the end is 2

## Algorithm to find the Nth node from the end (using the length of the linked list)

• Input the number of nodes of the linked list.
• Input all the nodes and create the linked list.
• Input the Nth node to be returned from the end of the linked list.
• Find the length of the linked list.
• Return (length - N + 1)th node.

## Program to return the Nth node from the end of a linked list using length

C
C++

Output
Input - Enter the number of nodes : 7 Enter the data for the nodes : 19 11 7 9 9 11 26 Linked List : 26--> 11--> 9--> 7-->7 -->11 -->19 Enter value of N : 3 Output - Nth node from the end : 7

Time complexity: O(n)

## Algorithm to find the Nth node from the end (using two pointers)

• Input the number of nodes of the linked list.
• Input all the nodes and create the linked list.
• Input the Nth node to be returned from the end of the linked list.
• Initialize both the reference pointer and the main pointer to the head node.
• First, move reference pointer to n nodes from the head node.
• Now, move both the pointers one by one until the reference pointer reaches the end of the list.
• Now, the main pointer will point to the nth node from the end.
• Return the main pointer.

## Program to find the Nth node from the end of the linked list using two pointers

C
C++

Output
Input - Enter the number of nodes : 7 Enter the data for the nodes : 19 11 7 9 9 11 26 Linked List : 26--> 11--> 9--> 7-->7 -->11 -->19 Enter value of N : 3 Output - Nth node from the end : 7

Recommended Programs