-
-
Notifications
You must be signed in to change notification settings - Fork 610
/
LinkedListRandomNode.java
49 lines (41 loc) · 1.08 KB
/
LinkedListRandomNode.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
package problems.medium;
import problems.utils.ListNode;
/**
* Created by sherxon on 1/2/17.
*/
// there are two solutions 1) with arraylist 2) without any extra space
public class LinkedListRandomNode {
ListNode head;
//List<ListNode> a;
ListNode x;
/**
* Returns a random node's value.
*/
int count = 0;
/** @param head The linked list's head.
Note that the head is guaranteed to be not null, so it contains at least one node. */
public LinkedListRandomNode(ListNode head) {
this.head=head;
this.x=head;
// ListNode x=head;
// a= new ArrayList<>();
// while(x!=null){
// a.add(x);
// x=x.next;
// }
}
public int getRandom() {
// int rand=(int) (Math.random()*a.size());
// return a.get(rand).val;
ListNode rr=head;
if(x!=null){
count++;
rr=x;
x=x.next;
}else{
int rand=(int)(Math.random()*count);
for(int i =1; i<=rand; i++)rr=rr.next;
}
return rr.val;
}
}