File tree Expand file tree Collapse file tree 1 file changed +34
-1
lines changed
Chapter1_Fundamentals/c1_3_bags_queues_stacks Expand file tree Collapse file tree 1 file changed +34
-1
lines changed Original file line number Diff line number Diff line change 1
1
package c1_3_bags_queues_stacks ;
2
2
3
+ import java .util .Iterator ;
4
+ import java .util .NoSuchElementException ;
3
5
import java .util .Random ;
4
6
5
- public class RandomQueue <Item > {
7
+ public class RandomQueue <Item > implements Iterable < Item > {
6
8
private int N ;
7
9
private int first ;
8
10
private Item [] list ;
@@ -54,4 +56,35 @@ private void resize(int max){
54
56
list = temp ;
55
57
first = 0 ;
56
58
}
59
+
60
+ @ Override
61
+ public Iterator <Item > iterator (){
62
+ return new ArrayIterator ();
63
+ }
64
+
65
+ private class ArrayIterator implements Iterator <Item >{
66
+ private int i = 0 ;
67
+
68
+ public ArrayIterator (){
69
+ randomSort ();
70
+ }
71
+
72
+ private void randomSort (){
73
+ for (int i = 0 ; i < N ; i ++){
74
+ int randIndex = i + rand .nextInt (N - i );
75
+ Item item = list [i ];
76
+ list [i ] = list [randIndex ];
77
+ list [randIndex ] = item ;
78
+ }
79
+ }
80
+
81
+ public boolean hasNext (){
82
+ return i < N ;
83
+ }
84
+ public Item next (){
85
+ if (!hasNext ())
86
+ throw new NoSuchElementException ();
87
+ return list [i ++];
88
+ }
89
+ }
57
90
}
You can’t perform that action at this time.
0 commit comments