- Write a function to get Nth node in a Linked List?
Algorithm:
- Initialize count = 0
- 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.
<script>
class Node {
constructor(d) {
this.data = d;
this.next = null;
}
}
var head;
function GetNth(index)
{
var current = head;
var count = 0;
while (current != null) {
if (count == index)
return current.data;
count++;
current = current.next;
}
assert (false);
return 0;
}
function push(new_data) {
var new_Node = new Node(new_data);
new_Node.next = head;
head = new_Node;
}
push(1);
push(4);
push(1);
push(12);
push(1);
document.write("Element at index 3 is "
+ GetNth(3));
</script>