-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path382.go
More file actions
43 lines (38 loc) · 807 Bytes
/
382.go
File metadata and controls
43 lines (38 loc) · 807 Bytes
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
package main
import (
"crypto/rand"
"math/big"
)
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
type Solution struct {
node *ListNode
}
/** @param head The linked list's head.
Note that the head is guaranteed to be not null, so it contains at least one node. */
func Constructor(head *ListNode) Solution {
return Solution{head}
}
/** Returns a random node's value. */
func (this *Solution) GetRandom() int {
p := this.node
q := p.Val
for i := 1; p != nil; i++ {
result, _ := rand.Int(rand.Reader, big.NewInt(int64(i)))
if result.Int64() == 0 {
q = p.Val
}
p = p.Next
}
return q
}
/**
* Your Solution object will be instantiated and called as such:
* obj := Constructor(head);
* param_1 := obj.GetRandom();
*/