Home >>Cpp Programs >C++ Program to find Nth node in Linked List

# C++ Program to find Nth node in Linked List

### C++ Program to find Nth node in Linked List

In this example, we'll see a C++ program through which we will find a node in a Linked list.

Algorithm:
• Step 1: First, declare the recursive function with parameters (Node * head, int data).
• Step 2: Then, Put the Node *temp = head, int index = 0;
• Step 3: Repeat Step 4 and Step 5 while (temp!= NULL)
• Step 4: if(temp -> data == data) then return index.
• Step 5: else index++ and temp = temp->next; then return -1.
Program:
``````
#include <bits/stdc++.h>
using namespace std;
int data;
Node * next;
};
Node *newNode(int k){ //defining new node
Node *temp = (Node*)malloc(sizeof(Node));
temp->data = k;
temp->next = NULL;
return temp;
}
//Used to add new node at the end of the list
}
else{
Node * node = newNode(k);
while(temp->next!= NULL){
temp = temp->next;
}
temp-> next = node;
}
}
Node *createNewLL(){
int cont = 1;
int data;
while(cont){
cout<<"Enter the data of the Node"<<endl;
cin>>data;
cout<<"Do you want to continue?(0/1)"<<endl;
cin>>cont;
}
}
//Function for finding the node
//Used to keep track of the Node Index
int index = 0;
//LinkedList traversal for finding the node
while(temp!=NULL){
if(temp->data == data){
//If element found return index
return index;
}
temp = temp->next;
index++;
}
return -1;
}
//Driver Main
int main(){
int data;
cout<<"Enter the data of the linked list to be found."<<endl;
cin>>data;
cout<<"It is present at "<<index<< endl;
return 0;
}
```
```
Output:
Enter the data of the Node
1
Do you want to continue?(0/1)
1
Enter the data of the Node
2
Do you want to continue?(0/1)
1
Enter the data of the Node
3
Do you want to continue?(0/1)
1
Enter the data of the Node
4
Do you want to continue?(0/1)
1
Enter the data of the Node
5
Do you want to continue?(0/1)
0
Enter the data of the linked list to be found.
3
It is present at 2