The Program in C++ Program to get Nth node in a given Singly Linked List is given below:
#include <iostream>
using namespace std;
struct Node {
int data;
Node* next;
};
Node* head = NULL; // global variable, points to the head of the linked list
void insert_at_end(int x) {
Node* temp = new Node();
temp->data = x;
temp->next = NULL;
if (head == NULL) {
head = temp;
return;
}
Node* p = head;
while (p->next != NULL)
p = p->next;
p->next = temp;
}
int get_nth_node(int n) {
Node* p = head;
int count = 0;
while (p != NULL) {
count++;
if (count == n)
return p->data;
p = p->next;
}
return -1;
}
int main() {
int n, x, k;
cout << "Hello Codeauri Family,enter the number of elements here: ";
cin >> n;
for (int i = 0; i < n; i++) {
cout << "Similarly,enter element " << i + 1 << ": ";
cin >> x;
insert_at_end(x);
}
cout << "Enter the position of the node (1-based indexing): ";
cin >> k;
int node_data = get_nth_node(k);
if (node_data == -1)
cout << "Invalid position. Please enter a valid position." << endl;
else
cout << "Okay,the data of the node at position " << k << " is: " << node_data << endl;
return 0;
}
Output:
Hello Codeauri Family,enter the number of elements here: 3
Similarly,enter element 1: 567
Similarly,enter element 2: 245
Similarly,enter element 3: 908
Enter the position of the node (1-based indexing): 3
Okay,the data of the node at position 3 is: 908
Pro-Tips💡
The program first takes the number of elements (n) to be added to the linked list from the user.
Then, it takes n elements as input and adds them to the linked list using the insert_at_end()
function. This function creates a new node and appends it to the end of the linked list.
After creating the linked list, the program takes an input from the user, which is the position of the node they want to retrieve (1-based indexing).
Then, it calls the get_nth_node()
function, which takes the position as an argument and returns the data of the node at that position.
The function get_nth_node()
uses a while loop to traverse the linked list and keeps count of the current node using a counter variable.
If the counter reaches the desired position, it returns the data of the current node.
If the position is greater than the number of nodes in the linked list, the function returns -1, indicating an invalid position.
Learn C-Sharp ↗
C-sharp covers every topic to learn about C-Sharp thoroughly.
Learn C Programming ↗
C-Programming covers every topic to learn about C-Sharp thoroughly.
Learn C++ Programming↗
C++ covers every topic to learn about C-Sharp thoroughly.