-
Notifications
You must be signed in to change notification settings - Fork 14
/
RecursiveIterator.java
59 lines (50 loc) · 1.62 KB
/
RecursiveIterator.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
package by.andd3dfx.iterators;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.Iterator;
import java.util.NoSuchElementException;
/**
* <pre>
* Дан итератор CustomIterator<Object>, который может возвращать String или CustomIterator.
* Возможная вложенность внутренних итераторов неограниченна.
*
* Написать для него методы next() и hasNext()
* </pre>
*
* @see <a href="https://youtu.be/dnR4xhkdx1I">Video solution</a>
*/
public class RecursiveIterator<Object> implements Iterator<Object> {
private Deque<Iterator<Object>> stack = new ArrayDeque<>();
public RecursiveIterator(Iterator<Object> iterator) {
stack.push(iterator);
}
@Override
public boolean hasNext() {
if (stack.isEmpty()) {
return false;
}
Iterator<Object> currentIterator = stack.peek();
if (currentIterator.hasNext()) {
return true;
}
stack.pop();
return hasNext();
}
@Override
public Object next() {
if (stack.isEmpty()) {
throw new NoSuchElementException();
}
Iterator<Object> currentIterator = stack.peek();
if (!currentIterator.hasNext()) {
stack.pop();
return next();
}
Object object = currentIterator.next();
if (object instanceof String) {
return object;
}
stack.push((Iterator<Object>) object);
return next();
}
}