Recursive Approach to find nth node from the end in the linked list in C++

Given a Singly linked list and positive integer N as input. The goal is to find the Nth node from the end in the given list using recursion. If the input list has nodes a → b → c → d → e → f and N is 4 then the 4th node from the end will be c.

We will first traverse till the last node in the list and while returning from recursion (backtracking) increment count. When count is equal to N then return pointer to current node as result.

Let us see various input output scenarios for this −

Input − List :- 1 → 5 → 7 → 12 → 2 → 96 → 33 N=3

Output − Nth Node from the last is: 2

Explanation − 3rd last node is 2.

Input − List :- 12 → 53 → 8 → 19 → 20 →96 → 33 N=8

Output − Node does not exist.

Explanation − The list has only 7 nodes so there will be no 8th last node possible.

Approach used in the below program is as follows

In this approach we will first reach the end of the list using recursion and while backtracking we will increment a static count variable. As soon as count becomes equal to input N, return the current node pointer.

• Take the structure Node with int data part and Node as next pointer.

• Create a singly linked list using the above function with head as pointer to first node.

• Take N as a positive integer.

• Function findNode(Node* head, int n1) takes pointer to head and n1 and prints the result when n1th node from the end is found.

• Take blast as pointer to the n1th node from the end.

• Call searchNthLast(head, n1, &nlast) to find that node.

• Function searchNthLast(Node* head, int n1, Node** nlast) returns the pointer to n1th last node from the end in linked list with head as first node.

• Take a static count variable.

• If head is NULL return nothing.

• Call searchNthLast(tmp, n1, nlast) to recursively traverse till the last node.

• After that increment count by 1.

• If count becomes equal to n1 then set *nlast=head.

• At the end print the value of the node pointed by nlast as result.

Example

#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
Node* next;
};
Node* nodex = new Node;
nodex->data = data;
}
void searchNthLast(Node* head, int n1, Node** nlast){
static int count=0;
return;
}
searchNthLast(tmp, n1, nlast);
count = count + 1;
if (count == n1){
}
}
Node* nlast = NULL;
if (nlast == NULL){
cout << "Node does not exists";
}
else{
cout << "Nth Node from the last is: "<< nlast->data;
}
}
if (curr != NULL){
cout<<curr->data<<" ";
display(curr->next);
}
}
int main(){
int N = 2;
cout<<endl;
return 0;
}

Output

If we run the above code it will generate the following Output

Linked list is :
5 4 10 8 15 12 20
Nth Node from the last is: 12