Skip to content

Commit 00a767e

Browse files
committed
src/bin/linked-list-random-node.rs
1 parent 2b0bb54 commit 00a767e

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed

src/bin/linked-list-random-node.rs

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
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+
}

0 commit comments

Comments
 (0)