Implement check, create and iterate

This commit is contained in:
2021-09-05 15:27:17 +02:00
parent 78fcf375a4
commit afe2bd6553
2 changed files with 55 additions and 8 deletions

View File

@ -3,4 +3,10 @@ package aud.exam.prep.list;
import aud.exam.prep.SequenceProcessor;
abstract class DoubleListItemProcessor<T> implements SequenceProcessor<T, DoubleListItem<T>> {
@Override
public Iterable<T> iterate(DoubleListItem<T> list) {
return () ->
new ListItemIterator<>(list);
}
}

View File

@ -3,6 +3,8 @@ package aud.exam.prep.list;
import aud.exam.prep.Pair;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Iterator;
public class RecursiveDoubleListItemProcessor<T> extends DoubleListItemProcessor<T> {
@ -176,19 +178,58 @@ public class RecursiveDoubleListItemProcessor<T> extends DoubleListItemProcessor
@Override
public boolean check(DoubleListItem<T> list) {
// TODO: Your training
throw new RuntimeException("unimplemented");
return checkRec(list, new HashSet<>(), null);
}
private boolean checkRec(DoubleListItem<T> list, HashSet<DoubleListItem<T>> seen, DoubleListItem<T> prev) {
if (list == null) {
if (seen.isEmpty()) {
return true;
}
if (prev == null) {
return true;
}
return prev.next == null;
}
if (list.prev != prev) {
return false;
}
if (prev != null && prev.next != list) {
return false;
}
if (list.key == null) {
return false;
}
if (seen.contains(list)) {
return false;
}
seen.add(list);
return checkRec(list.next, seen, list);
}
@Override
public DoubleListItem<T> create(Iterable<T> iterable) {
// TODO: Your training
throw new RuntimeException("unimplemented");
var iter = iterable.iterator();
return createRec(iter, null);
}
@Override
public Iterable<T> iterate(DoubleListItem<T> list) {
// TODO: Your training
throw new RuntimeException("unimplemented");
private DoubleListItem<T> createRec(Iterator<T> iter, DoubleListItem<T> prev) {
if (!iter.hasNext()) {
return null;
}
var item = new DoubleListItem<T>();
item.key = iter.next();
item.next = createRec(iter, item);
item.prev = prev;
return item;
}
}