Junior — Senior
Handling potential null values in the get method of a linked list
livecode
Task condition
It is necessary to clarify how the get method should behave when the value stored in the node can be null. It needs to be determined whether the presence of one or more such nodes is allowed and how this affects the returned result.
@Override
public Optional<T> get(int targetIdx) {
// set position = 0
// traverse the chain until next is null
int pos = 0;
for (int i = 0; i < targetIdx; i++) {
if (pos == targetIdx) {
return Optional.ofNullable(item);
}
pos++;
}
return Optional.empty();
}