File tree Expand file tree Collapse file tree 1 file changed +59
-0
lines changed Expand file tree Collapse file tree 1 file changed +59
-0
lines changed Original file line number Diff line number Diff line change 1+ use rand:: Rng ;
2+
3+ fn main ( ) { }
4+
5+ // Definition for singly-linked list.
6+ #[ derive( PartialEq , Eq , Clone , Debug ) ]
7+ pub struct ListNode {
8+ pub val : i32 ,
9+ pub next : Option < Box < ListNode > > ,
10+ }
11+
12+ impl ListNode {
13+ #[ inline]
14+ fn new ( val : i32 ) -> Self {
15+ ListNode {
16+ next : None ,
17+ val,
18+ }
19+ }
20+ }
21+
22+ /**
23+ * Your Solution object will be instantiated and called as such:
24+ * let obj = Solution::new(head);
25+ * let ret_1: i32 = obj.get_random();
26+ */
27+ struct Solution {
28+ head : Option < Box < ListNode > >
29+ }
30+
31+
32+ /**
33+ * `&self` means the method takes an immutable reference.
34+ * If you need a mutable reference, change it to `&mut self` instead.
35+ */
36+ impl Solution {
37+ /** @param head The linked list's head.
38+ Note that the head is guaranteed to be not null, so it contains at least one node. */
39+ fn new ( head : Option < Box < ListNode > > ) -> Self {
40+ Self { head }
41+ }
42+
43+ /** Returns a random node's value. */
44+ fn get_random ( & self ) -> i32 {
45+ use rand:: Rng ;
46+ let mut s = & self . head ;
47+ let mut n = 1 ;
48+ let mut r = 0 ;
49+ while let Some ( x) = s {
50+ if rand:: thread_rng ( ) . gen_range ( 0 ..n) == 0 {
51+ r = x. val ;
52+ }
53+
54+ s = & x. next ;
55+ n += 1 ;
56+ }
57+ r
58+ }
59+ }
You can’t perform that action at this time.
0 commit comments