C++ Program For Writing A Function To Get Nth Node In A Linked List
Write a C++ Program to GetNth() function that takes a linked list and an integer index and returns the data value stored in the node at that index position.
Example:
Input: 1->10->30->14, index = 2
Output: 30
The node at index 2 is 30
Algorithm:
1. Initialize count = 0
2. Loop through the linkList
a. If count is equal to the passed index then return current
node
b. Increment count
c. change current to point to next of the current.
Implementation:
C++
#include <assert.h>
#include <bits/stdc++.h>
using namespace std;
class Node {
public :
int data;
Node* next;
};
void push(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 GetNth(Node* head, int index)
{
Node* current = head;
int count = 0;
while (current != NULL) {
if (count == index)
return (current->data);
count++;
current = current->next;
}
assert (0);
}
int main()
{
Node* head = NULL;
push(&head, 1);
push(&head, 4);
push(&head, 1);
push(&head, 12);
push(&head, 1);
cout << "Element at index 3 is " << GetNth(head, 3);
return 0;
}
|
Output
Element at index 3 is 4
Time Complexity: O(n)
Space complexity: O(1) using only constant variables
C++ Program For Writing A Function To Get Nth Node In A Linked List using Recursion:
Algorithm:
getnth(node,n)
1. Initialize count = 0
2. if count==n
return node->data
3. else
return getnth(node->next,n-1)
Implementation:
C++
#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
struct Node* next;
};
void push( struct Node** head_ref, int new_data)
{
struct Node* new_node
= ( struct Node*) malloc ( sizeof ( struct Node));
new_node->data = new_data;
new_node->next = (*head_ref);
(*head_ref) = new_node;
}
int GetNth( struct Node* head, int n)
{
if (head == NULL)
return -1;
if (n == 0)
return head->data;
return GetNth(head->next, n - 1);
}
int main()
{
struct Node* head = NULL;
push(&head, 1);
push(&head, 4);
push(&head, 1);
push(&head, 12);
push(&head, 1);
printf ( "Element at index 3 is %d" , GetNth(head, 3));
getchar ();
}
|
Output
Element at index 3 is 4
Time Complexity: O(n)
Space Complexity: O(n) since using constant space to create nodes.
Please refer complete article on Write a function to get Nth node in a Linked List for more details!
Last Updated :
12 Oct, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...