Javascript Program For Writing A Function To Get Nth Node In A Linked List
Last Updated :
31 Jul, 2023
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 = 2
Output: 30
Explanation: The node at index 2 is 30
Method 1 – Using Loop
Algorithm:
1. Initialize count = 0
2. Loop through the link list
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:
Javascript
class Node {
constructor(d) {
this .data = d;
this .next = null ;
}
}
let head;
function GetNth(index) {
let current = head;
let count = 0;
while (current != null ) {
if (count == index)
return current.data;
count++;
current = current.next;
}
assert( false );
return 0;
}
function push(new_data) {
let new_Node = new Node(new_data);
new_Node.next = head;
head = new_Node;
}
push(1);
push(4);
push(1);
push(12);
push(1);
console.log( "Element at index 3 is " +
GetNth(3));
|
Output
Element at index 3 is 4
Time Complexity: O(n)
Space Complexity: O(1) since using constant space to create nodes and variables.
Method 2 – 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:
Javascript
class Node {
constructor(val) {
this .data = val;
this .next = null ;
}
}
function push(head, new_data) {
let new_node = new Node(new_data);
new_node.data = new_data;
new_node.next = head;
head = new_node;
return head;
}
function GetNth(head, n) {
let count = 0;
if (head == null )
return -1;
if (count == n)
return head.data;
return GetNth(head.next, n - 1);
}
let head = null ;
head = push(head, 1);
head = push(head, 4);
head = push(head, 1);
head = push(head, 12);
head = push(head, 1);
console.log( "Element at index 3 is " ,
GetNth(head, 3));
|
Output
Element at index 3 is 4
Time Complexity: O(n)
Space Complexity: O(n) for call stack because using recursion
Please refer complete article on Write a function to get Nth node in a Linked List for more details!
Share your thoughts in the comments
Please Login to comment...