-
Notifications
You must be signed in to change notification settings - Fork 1
/
RandomizedQueue.java
139 lines (111 loc) · 3.12 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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
import edu.princeton.cs.algs4.StdRandom;
import edu.princeton.cs.algs4.StdOut;
import java.util.Iterator;
import java.util.NoSuchElementException;
public class RandomizedQueue<Item> implements Iterable<Item> {
private class Node {
Item data;
Node next;
public Node(Item d) {
data = d;
next = null;
}
}
private class RandomizedQueueIterator implements Iterator<Item> {
private Node current;
public void remove() {
throw new UnsupportedOperationException();
}
public boolean hasNext() {
return current != null;
}
public Item next() {
if (current == null) {
throw new NoSuchElementException();
}
Item temp = current.data;
current = current.next;
return temp;
}
}
private Node first;
private int size;
public RandomizedQueue() {
size = 0;
first = null;
}
public boolean isEmpty() {
return first == null;
}
public int size() {
return size;
}
public void enqueue(Item item) {
if (item == null) {
throw new IllegalArgumentException();
}
Node temp = new Node(item);
size++;
if (!isEmpty()) {
temp.next = first;
}
first = temp;
}
public Item dequeue() {
if (isEmpty()) {
throw new NoSuchElementException();
}
int number = StdRandom.uniform(1, size + 1);
number--;
if (number == 0) {
Item item = first.data;
first = first.next;
size--;
return item;
}
Node temp = first;
Node back = null;
while (number > 0) {
back = temp;
temp = temp.next;
number--;
}
back.next = temp.next;
size--;
return temp.data;
}
public Item sample() {
if (isEmpty()) {
throw new NoSuchElementException();
}
int number = StdRandom.uniform(1, size + 1);
number--;
Node temp = first;
while (number > 0) {
temp = temp.next;
number--;
}
return temp.data;
}
public Iterator<Item> iterator() {
return new RandomizedQueueIterator();
}
public static void main(String[] args) {
String[] string = {"a", "b", "c", "d", "e"};
RandomizedQueue<String> queue = new RandomizedQueue<>();
StdOut.println("Size " + queue.size() + ", isempty: " + queue.isEmpty());
for (String s : string) {
queue.enqueue(s);
StdOut.println("Size " + queue.size() + ", isempty: " + queue.isEmpty());
}
StdOut.println("======");
for (int i = 0; i < queue.size(); ++i) {
StdOut.println(queue.sample());
}
StdOut.println("======");
while (!queue.isEmpty()) {
StdOut.println(queue.dequeue());
StdOut.println("Size " + queue.size() + ", isempty: " + queue.isEmpty());
}
}
}