VOOZH about

URL: https://www.geeksforgeeks.org/dsa/write-a-function-to-get-nth-node-in-a-linked-list/

⇱ Write a function to get Nth node in a Linked List - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Write a function to get Nth node in a Linked List

Last Updated : 23 Jul, 2025

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 = 2
Output: 10
Explanation: The node value at index 2 is 10

👁 Maximum-of-all-subarrays-of-size-K


Input: 1->32->12->10->30->14->100, index = 8
Output: -1
Explanation: No such node exists at index = 8.

[Naive Approach] Recursive Method - O(n) Time and O(n) Space

The idea is to use the recursive method to find the value of index node (1- based) . Call the function GetNth(head,index) recusively, where head will represent the current head node . Decrement the index value by 1 on every recursion call. When the n reaches 1 ,we will return the data of current node.

Below is the implementation of above approach: 


Output
Element at index 3 is 3

Time Complexity : O(n) ,where n is the nth node of linked list.
Auxiliary Space: O(n), for recursive call stack

[Expected Approach-2] Iterative Method - O(n) Time and O(1) Space

The idea is similar to recursive approach to find the value at index node (1- based) .We will use a variable say, count = 1 to track the nodes. Traverse the list until curr != NULL . Increment the count if count is not equal to index node (1- based) , else if count equals to the index node, return data at current node.

Below is the implementation of above approach :


Output
Element at index 3 is 3

Time Complexity : O(n), where n is the nth node of linked list.
Auxiliary Space: O(1)

Comment