1 parent 127bdae commit b9baf04Copy full SHA for b9baf04
1 file changed
solutions/382. Linked List Random Node/LinkedListRandomNode.java
@@ -0,0 +1,37 @@
1
+package leetcode;
2
+
3
+import java.util.Random;
4
5
+public class LinkedListRandomNode {
6
7
+ public class ListNode{
8
+ private ListNode next;
9
+ private int val;
10
11
+ public ListNode(int val){
12
+ this.val = val;
13
+ }
14
15
16
+ private ListNode head;
17
+ private Random random;
18
19
+ public LinkedListRandomNode(ListNode head){
20
+ this.head = head;
21
+ this.random = new Random();
22
23
24
+ /** Returns a random node's value. */
25
+ // ÐîË®³ØËã·¨
26
+ public int getRandom() {
27
+ ListNode res = null;
28
+ ListNode p = this.head;
29
+ for(int i = 1; p != null; i++, p = p.next ){
30
+ if(random.nextInt(i) == 0){
31
+ res = p;
32
33
34
35
+ return res.val;
36
37
+}
0 commit comments