public class ListItem {
final int number;
ListItem next;
public static ListItem evenElements(ListItem ls) {
ListItem l = ls.duplicate();
if(ls == null){
return null;
}
else{
for(int i = 0; i < ls.length(); i++){
if(ls.number % 2 == 0){
l = ls;
ls = ls.next;
}
else{
ls = ls.next;
}
}
return l;
}
}
When I run this code of a list of items: [3,2,6,9]
, it returns [2,6,9]
when it should only return [2,6]
. The duplicate method duplicates the ListItem, and the length method determines the length of the list. How can I fix this issue?
If I try to keep your logic: