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
[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 thecountif 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)