- Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathlinked-list-random-node.rs
57 lines (49 loc) · 1.26 KB
/
linked-list-random-node.rs
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
#![allow(dead_code, unused, unused_variables)]
use rand::Rng;
fnmain(){}
// Definition for singly-linked list.
#[derive(PartialEq,Eq,Clone,Debug)]
pubstructListNode{
pubval:i32,
pubnext:Option<Box<ListNode>>,
}
implListNode{
#[inline]
fnnew(val:i32) -> Self{
ListNode{next:None, val }
}
}
/**
* Your Solution object will be instantiated and called as such:
* let obj = Solution::new(head);
* let ret_1: i32 = obj.get_random();
*/
structSolution{
head:Option<Box<ListNode>>,
}
/**
* `&self` means the method takes an immutable reference.
* If you need a mutable reference, change it to `&mut self` instead.
*/
implSolution{
/** @param head The linked list's head.
Note that the head is guaranteed to be not null, so it contains at least one node. */
fnnew(head:Option<Box<ListNode>>) -> Self{
Self{ head }
}
/** Returns a random node's value. */
fnget_random(&self) -> i32{
use rand::Rng;
letmut s = &self.head;
letmut n = 1;
letmut r = 0;
whileletSome(x) = s {
if rand::thread_rng().gen_range(0..n) == 0{
r = x.val;
}
s = &x.next;
n += 1;
}
r
}
}