C++ program to get Nth node in a Linked List
In this tutorial, we are going to discuss how to get the Nth node in a singly linked list in C++.
Let us have a look at the examples given below.
Example:
Input : 10->15->20->25, index=3 Output : 25 The node at index 3 is 25. Input : 11->12->13->14->15, index=2 Output : 13 The node at index 2 is 13.
Algorithm:
- Initialize a count variable, count=0
- Traverse through the link list
- if count is equal to the current index then return the current node,
- else increment the count and change the current to point to the immediate next.
Implementation: Find Nth node in a Linked List in C++
//C++ code to get the'N'th node in Linked List #include<bits/stdc++.h> #include<assert.h> using namespace std; //Linked List Node struct node { int data; struct node* next; }; //function to create a new node node *newnode(int data) { struct node *temp=new node; temp->data=data; temp->next=NULL; return temp; } //function that takes head of linked list and index //and returns the data at that index int getNth(node *head,int index) { //initializing the current node as the head node* current=head; //initializing the count variable int count=0; while(current!=NULL) { if(count==index) //returning the data at the given index return current->data; //incrementing the count variable count++; //incrementing the current next current=current->next; } //if the user is asking for a non-existent element so we assert fail assert(0); } //Dry run program to testify the getNth() function int main() { //creating a linked list struct node* head=newnode(10); head->next=newnode(15); head->next->next=newnode(20); head->next->next->next=newnode(25); //checking the getNth() function cout<<"Element at index 3 is " << getNth(head,3); return 0; }
Output:
Element at index 3 is 25
I hope this tutorial helps you understand how to get the Nth element in a linked list in a better way.
Leave a Reply