forked from rampatra/Algorithms-and-Data-Structures-in-Java
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRandomNode.java
54 lines (45 loc) · 1.37 KB
/
RandomNode.java
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
package me.ramswaroop.linkedlists;
import me.ramswaroop.common.SingleLinkedList;
import me.ramswaroop.common.SingleLinkedNode;
import java.util.Random;
/**
* Created by IntelliJ IDEA.
*
* @author: ramswaroop
* @date: 7/21/15
* @time: 12:57 PM
*/
public class RandomNode {
/**
* Returns a random node from linked list with each node having an equal probability.
*
* This method uses the simplified version of Reservoir Sampling ({@link me.ramswaroop.arrays.ReservoirSampling})
* where k = 1.
*
* @param node
* @param <E>
* @return
*/
public static <E extends Comparable<E>> SingleLinkedNode<E> getRandomNode(SingleLinkedNode<E> node) {
SingleLinkedNode<E> result = node, curr = node;
for (int i = 2; curr != null; i++) {
int rand = new Random().nextInt(i);
if (rand % i == 0) result = curr;
curr = curr.next;
}
return result;
}
public static void main(String a[]) {
SingleLinkedList<Integer> linkedList = new SingleLinkedList<>();
linkedList.add(00);
linkedList.add(11);
linkedList.add(22);
linkedList.add(33);
linkedList.add(44);
linkedList.add(55);
linkedList.add(66);
linkedList.add(77);
linkedList.add(88);
System.out.println(getRandomNode(linkedList.head).item);
}
}