I've been working on a practice problem. The idea is that I'm supposed to take a linked list, then apply a unary transformer to the list, and return the modified list. I'm not applying a specific change, just process and return a linked list. Here's the breakdown, along with the UnaryTransformer method provided by the instructions:
"If L is the head of a linked list of objects of the type Q and R is a UnaryTransformer, then transformAll(L,R) is the linked list of objects obtained by applying R to every object in L in order."
{@code UnaryTransformer} objects are used to represent functions with the signature:
public interface UnaryTransformer<Q> {
/**
* Returns the result of applying a function modeled by
* {@code UnaryTransformer} to the given object
*
* @param object the object to transform
* @return the result of applying a function
*/
Q apply(Q object);
}
So far I have this code, but it doesn't compile.
public static transformAll(Node L, R) {
if (L != null) {
LinkedList<Q> sequence = new LinkedList<Q>();
for (int i = 0; i < size(); i++) {
if (p.apply(get(i))){
sequence.add(get(i));
}
}
return sequence;
}
}
You were close! Assuming your get
method returns an element of the LinkedList
at index i
, calling it twice would return the same element regardless if it was mapped. You should pass the result of R.apply
directly to the new LinkedList
to assure that it is mapped:
public LinkedList<Q> transformAll(Node L, UnaryTransformer<Q> R) {
if (L == null) {
return null;
}
LinkedList<Q> sequence = new LinkedList<>();
for (int i = 0; i < size(); i++) {
sequence.add(R.apply(get(i)));
}
return sequence;
}
Keep in mind that get
for LinkedList
is an O(n)
operation, so this method is O(n^2)
. It can be mitigated by simply iterating over the LinkedList
directly.
Note: This assumes that this method is located within your LinkedList
class and Q
is the generic type of the list.