C++ Program For Writing A Function To Get Nth Node In A Linked List
Last Updated :
12 Oct, 2023
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++
// C++ program to find n'th
// node in linked list
#include <assert.h>
#include <bits/stdc++.h>
using namespace std;
// Link list node
class Node {
public:
int data;
Node* next;
};
/* Given a reference (pointer to
pointer) to the head of a list
and an int, push a new node on
the front of the list. */
void push(Node** head_ref, int new_data)
{
// Allocate node
Node* new_node = new Node();
// Put in the data
new_node->data = new_data;
// Link the old list
// of the new node
new_node->next = (*head_ref);
// Move the head to point
// to the new node
(*head_ref) = new_node;
}
// Takes head pointer of
// the linked list and index
// as arguments and return
// data at index
int GetNth(Node* head, int index)
{
Node* current = head;
// The index of the
// node we're currently
// looking at
int count = 0;
while (current != NULL) {
if (count == index)
return (current->data);
count++;
current = current->next;
}
/* If we get to this line,
the caller was asking
for a non-existent element
so we assert fail */
assert(0);
}
// Driver Code
int main()
{
// Start with the empty list
Node* head = NULL;
// Use push() to construct list
// 1->12->1->4->1
push(&head, 1);
push(&head, 4);
push(&head, 1);
push(&head, 12);
push(&head, 1);
// Check the count function
cout << "Element at index 3 is " << GetNth(head, 3);
return 0;
}
// This code is contributed by rathbhupendra
OutputElement 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++
// C++ program to find n'th node in
// linked list using recursion
#include <bits/stdc++.h>
using namespace std;
// Link list node
struct Node {
int data;
struct Node* next;
};
/* Given a reference (pointer to pointer)
to the head of a list and an int, push
a new node on the front of the list. */
void push(struct Node** head_ref, int new_data)
{
// Allocate node
struct Node* new_node
= (struct Node*)malloc(sizeof(struct Node));
// Put in the data
new_node->data = new_data;
// Link the old list of the new node
new_node->next = (*head_ref);
// Move the head to point to the new node
(*head_ref) = new_node;
}
/* Takes head pointer of the linked list and
index as arguments and return data at index.
(Don't use another variable)*/
int GetNth(struct Node* head, int n)
{
// If length of the list is less
// than the given index, return -1
if (head == NULL)
return -1;
// If n equal to 0 return node->data
if (n == 0)
return head->data;
// Increase head to next pointer
// n - 1: decrease the number of
// recursions until n = 0
return GetNth(head->next, n - 1);
}
// Driver code
int main()
{
// Start with the empty list
struct Node* head = NULL;
// Use push() to construct list
// 1->12->1->4->1
push(&head, 1);
push(&head, 4);
push(&head, 1);
push(&head, 12);
push(&head, 1);
// Check the count function
printf("Element at index 3 is %d", GetNth(head, 3));
getchar();
}
OutputElement 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!
Similar Reads
Javascript Program For Writing A Function To Get Nth Node In A Linked List Write a 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 = 2Output: 30 Explanation: The node at index 2 is 30Recommended: Please solve it on "PRACTICE" first, befo
4 min read
Write a function to get Nth node in a Linked List Given a LinkedList and an index (1-based). The task is to find the data value stored in the node at that kth position. If no such node exists whose index is k then return -1.Example:Â Input: 1->10->30->14, index = 2Output: 10Explanation: The node value at index 2 is 10 Input: 1->32->12
11 min read
Program for Nth node from the end of a Linked List Given a Linked List of M nodes and a number N, find the value at the Nth node from the end of the Linked List. If there is no Nth node from the end, print -1.Examples:Input: 1 -> 2 -> 3 -> 4, N = 3Output: 2Explanation: Node 2 is the third node from the end of the linked list.Input: 35 ->
14 min read
Menu driven program for all operations on singly linked list in C A Linked List is a linear data structure that consists of two parts: one is the data part and the other is the address part. In this article, all the common operations of a singly linked list are discussed in one menu-driven program.Operations to be PerformedcreateList(): To create the list with the
8 min read
Search an Element in Doubly Circular Linked List Pre-requisite: Convert an Array to a Circular Doubly Linked List, Doubly Circular Linked ListGiven a doubly circular linked list. The task is to find the position of an element in the list. Image Representation: Algorithm: Declare a temp pointer, and initialize it to the head of the list.Iterate the
13 min read
Traversal of Singly Linked List Traversal of Singly Linked List is one of the fundamental operations, where we traverse or visit each node of the linked list. In this article, we will cover how to traverse all the nodes of a singly linked list along with its implementation. Examples:Input: 1->2->3->4->5->nullOutput:
11 min read