-
Notifications
You must be signed in to change notification settings - Fork 37
/
Copy pathQueueExample.java
82 lines (65 loc) · 1.93 KB
/
QueueExample.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
package Java;
import java.util.Arrays;
/**
* @author Michael Balakhon
* @link t.me/mibal_ua.
*/
public class QueueExample {
static class Queue {
private Element first;
private Element last;
private int count;
public void put(final String value) {
final Element element = new Element(first, value);
if (count == 0) {
first = element;
} else {
last.next = element;
}
last = element;
count++;
}
public String pick() {
if (count == 0) {
throw new NullPointerException("Queue is empty");
}
final Element result = first;
first = first.next;
count--;
if (count == 0 || count == 1) {
last = first;
}
return result.value;
}
public String[] asArray() {
final String[] result = new String[count];
Element current = first;
for (int j = 0; j < count; j++) {
result[j] = current.value;
current = current.next;
}
return result;
}
private static class Element {
private Element next;
private final String value;
public Element(final Element next, final String value) {
this.next = next;
this.value = value;
}
}
}
// Usage
public static void main(final String[] args) {
final Queue queue = new Queue();
queue.put("first");
queue.put("second");
queue.put("third");
String[] array = queue.asArray();
System.out.println(Arrays.toString(array));
System.out.println(queue.pick());
System.out.println(queue.pick());
System.out.println(queue.pick());
//System.out.println(queue.pick());
}
}