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
getmethod returns an element of theLinkedListat indexi, calling it twice would return the same element regardless if it was mapped. You should pass the result ofR.applydirectly to the newLinkedListto assure that it is mapped:Keep in mind that
getforLinkedListis anO(n)operation, so this method isO(n^2). It can be mitigated by simply iterating over theLinkedListdirectly.Note: This assumes that this method is located within your
LinkedListclass andQis the generic type of the list.