Skip to content

Commit 1fd974c

Browse files
committed
add
1 parent 22201c8 commit 1fd974c

File tree

1 file changed

+34
-1
lines changed

1 file changed

+34
-1
lines changed

Chapter1_Fundamentals/c1_3_bags_queues_stacks/RandomQueue.java

Lines changed: 34 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,10 @@
11
package c1_3_bags_queues_stacks;
22

3+
import java.util.Iterator;
4+
import java.util.NoSuchElementException;
35
import java.util.Random;
46

5-
public class RandomQueue<Item> {
7+
public class RandomQueue<Item> implements Iterable<Item>{
68
private int N;
79
private int first;
810
private Item[] list;
@@ -54,4 +56,35 @@ private void resize(int max){
5456
list = temp;
5557
first = 0;
5658
}
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+
}
5790
}

0 commit comments

Comments
 (0)