-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRandomizedQueue.java
109 lines (89 loc) · 2.23 KB
/
RandomizedQueue.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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
import java.util.Iterator;
import java.util.NoSuchElementException;
import edu.princeton.cs.algs4.StdRandom;
public class RandomizedQueue<Item> implements Iterable<Item> {
private int size;
private Node headPtr;
private class Node {
Item item;
Node next;
}
// construct an empty randomized queue
public RandomizedQueue() {
this.size = 0;
this.headPtr = null;
}
// is the randomized queue empty?
public boolean isEmpty() {
return this.size == 0;
}
// return the number of items on the randomized queue
public int size() {
return this.size;
}
// add the item
public void enqueue(Item item) {
if (item == null)
throw new IllegalArgumentException();
Node temp = new Node();
temp.item = item;
temp.next = this.headPtr;
this.headPtr = temp;
this.size += 1;
}
// remove and return a random item
public Item dequeue() {
if (this.size == 0)
throw new NoSuchElementException();
int idx = StdRandom.uniform(this.size);
Node temp = new Node();
temp = headPtr;
for (int i = 0; i < idx - 1; i++) {
temp = temp.next;
}
temp.next = temp.next.next;
this.size -= 1;
return temp.item;
}
// return a random item (but do not remove it)
public Item sample() {
if (this.size == 0)
throw new NoSuchElementException();
int idx = StdRandom.uniform(this.size);
Node temp = new Node();
temp = headPtr;
for (int i = 0; i < idx; i++) {
temp = temp.next;
}
return temp.item;
}
// return an independent iterator over items in random order
public Iterator<Item> iterator() {
return new RandomIterator();
}
private class RandomIterator implements Iterator<Item> {
private Node current = headPtr;
@Override
public boolean hasNext() {
// TODO Auto-generated method stub
return current != null;
}
@Override
public Item next() {
// TODO Auto-generated method stub
if (current == null) {
throw new NoSuchElementException();
}
Item item = current.item;
current = current.next;
return item;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
}
// unit testing (required)
public static void main(String[] args) {
}
}