Write a function to get Nth node in a Linked List in C++


Here, we are given a linked list and an index. We have to write a function to get Nth node in a linked list.

Let’s take an example to understand the problem,

Input

linked list = 34 -> 4 -> 9 -> 1 , n = 2

Output

9

To go to the node specified by n. We will go node by node in the linked list and increase the index count until the required nth position is reached.

Program to illustrate the program,

Example

 Live Demo

#include <iostream>
using namespace std;
class Node{
   public:
   int data;
   Node* next;
};
void insertNode(Node** head_ref, int new_data) {
   Node* new_node = new Node();
   new_node->data = new_data;
   new_node->next = (*head_ref);
   (*head_ref) = new_node;
}
int findNodeAt(Node* head, int index) {
   Node* current = head;
   int count = 0;
   while (current != NULL){
      if (count == index)
         return(current->data);
      count++;
      current = current->next;
   }
}
int main(){
   Node* head = NULL;
   insertNode(&head, 8);
   insertNode(&head, 2);
   insertNode(&head, 9);
   insertNode(&head, 1);
   insertNode(&head, 4);
   int n = 2;
   cout<<"Element at index "<<n<<" is "<<findNodeAt(head, 2);
   return 0;
}

Output

Element at index 2 is 9

Updated on: 20-Apr-2020

551 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements