-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path382_Linked List Random Node.js
57 lines (50 loc) · 1.17 KB
/
382_Linked List Random Node.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
// https://leetcode.com/problems/linked-list-random-node/description/
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
function ListNode(val) {
this.val = val;
this.next = null;
}
/**
* @param head The linked list's head.
Note that the head is guaranteed to be not null, so it contains at least one node.
* @param {ListNode} head
*/
var Solution = function (head) {
this.size = 0;
this.head = head;
var node = head;
while (node) {
this.size++;
node = node.next;
}
};
/**
* Returns a random node's value.
* @return {number}
*/
Solution.prototype.getRandom = function () {
var pos = parseInt(Math.random() * this.size, 10);
var node = this.head;
for (var i = 0; i < pos; i++) {
node = node.next;
}
return node.val;
};
/**
* Your Solution object will be instantiated and called as such:
* var obj = Object.create(Solution).createNew(head)
* var param_1 = obj.getRandom()
*/
var head = new ListNode(1);
head.next = new ListNode(2);
head.next.next = new ListNode(3);
var solution = new Solution(head);
for (let i = 0; i < 5; i++) {
console.log(solution.getRandom());
}