Linked List Random Node LeetCode solution in JavaScript
1var Solution = function (head) {2this.res = [];3let curr = head;45while (curr !== null) {6this.res.push(curr);7curr = curr.next;8}9this.length = this.res.length;10};1112Solution.prototype.getRandom = function () {13//Math.random() will generate a random number b/w 0 & 1.14//then multiply it with the array size, as i have all the value in the list, i know the size of the list15//take only the integer part which is a random index.16//return the element at that random index.17return this.res[Math.floor(Math.random() * this.length)].val;18};