-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFixedStack.java
More file actions
81 lines (68 loc) · 1.85 KB
/
FixedStack.java
File metadata and controls
81 lines (68 loc) · 1.85 KB
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
package me.koply.test.util;
import java.util.Iterator;
import java.util.Spliterator;
import java.util.function.Consumer;
// if stack is full
// overwrites last index
public class FixedStack<T> implements Iterable<T> {
/*
* it is a stack actually but size is fixed
* last in first out structure
*/
private final Object[] array;
public final int size;
private int cursor;
public FixedStack(int size) {
this.size = size;
this.array = new Object[size];
this.cursor = 0;
}
public void push(T object) {
array[cursor] = object;
if (cursor+1==size) cursor = 0;
else cursor++;
}
public void addAll(T...arr) {
for (T obj : arr) {
push(obj);
}
}
@SuppressWarnings("unchecked")
public T pop() {
if (cursor == 0) cursor = size-1;
else cursor--;
Object toreturn = array[cursor];
array[cursor] = null;
return (T) toreturn;
}
@Override
public Iterator<T> iterator() {
// final wrapper for anonymous class
final int lastCursor = cursor;
return new Iterator<>() {
int _cursor = lastCursor;
int i = 0;
@Override
public boolean hasNext() {
if (i==size) return false;
i++;
if (_cursor==0) _cursor = size-1;
else _cursor--;
return array[_cursor] != null;
}
@SuppressWarnings("unchecked")
@Override
public T next() {
return (T) array[_cursor];
}
};
}
@Override
public void forEach(Consumer<? super T> action) {
Iterable.super.forEach(action);
}
@Override
public Spliterator<T> spliterator() {
return Iterable.super.spliterator();
}
}