Programovanie (1) v C/C++
1-INF-127, ZS 2024/25
Riešenia vybraných úloh z cvičení č. 5
Skočit na navigaci
Skočit na vyhledávání
Úloha č. 5
import java.util.*;
public class ElementSubsetIterator<E> implements Iterator<E> {
private Iterator<E> iterator;
private Set<E> elements;
private E next;
private boolean hasNext;
public ElementSubsetIterator(Iterator<E> iterator, Set<E> elements) {
this.iterator = iterator;
this.elements = new HashSet<>(elements);
findNext();
}
private void findNext() {
hasNext = false;
while (iterator.hasNext() && !hasNext) {
E element = iterator.next();
if (elements.contains(element)) {
hasNext = true;
next = element;
}
}
}
@Override
public boolean hasNext() {
return hasNext;
}
@Override
public E next() {
if (hasNext()) {
E result = next;
findNext();
return result;
} else {
throw new NoSuchElementException();
}
}
}
Úloha č. 6
import java.util.*;
public class PalilalicIterator<E> implements Iterator<E> {
private Iterator<E> iterator;
private boolean emitted;
private E last;
public PalilalicIterator(Iterator<E> iterator) {
this.iterator = iterator;
}
@Override
public boolean hasNext() {
return emitted || iterator.hasNext();
}
@Override
public E next() {
if (emitted) {
emitted = false;
return last;
} else {
last = iterator.next();
emitted = true;
return last;
}
}
}