-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathImmutableQueue.java
70 lines (58 loc) · 1.8 KB
/
ImmutableQueue.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
package example6;
import common.IStack;
import common.Optional;
import common.Pair;
import example5.ImmutableStack;
public final class ImmutableQueue<T> {
private final IStack<T> enqueueStack;
private final IStack<T> dequeueStack;
private final int length;
private ImmutableQueue(IStack<T> enqueueStack, IStack<T> dequeueStack, int length) {
this.dequeueStack = dequeueStack;
this.enqueueStack = enqueueStack;
this.length = length;
}
public ImmutableQueue() {
dequeueStack = ImmutableStack.empty();
enqueueStack = ImmutableStack.empty();
length = 0;
}
public int size() {
return length;
}
public ImmutableQueue<T> enqueue(T value) {
return new ImmutableQueue<>(
enqueueStack.push(value),
dequeueStack,
length + 1
);
}
public Pair<Optional<T>, ImmutableQueue<T>> dequeue() {
if (!dequeueStack.isEmpty()) {
Pair<Optional<T>, IStack<T>> pair = dequeueStack.pop();
ImmutableQueue<T> newQueue = new ImmutableQueue<>(
enqueueStack,
pair.collection(),
length - 1
);
return Pair.of(pair.value(), newQueue);
}
else if (!enqueueStack.isEmpty()) {
IStack<T> newDequeueStack = enqueueStack.reversed();
ImmutableQueue<T> newQueue = new ImmutableQueue<>(
ImmutableStack.<T>empty(),
newDequeueStack,
length
);
return newQueue.dequeue();
}
else
return Pair.of(Optional.<T>absent(), this);
}
public Optional<T> peek() {
return dequeue().value();
}
public boolean isEmpty() {
return length == 0;
}
}