How do I find the even elements in a list of items?

995 views Asked by At
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?

1

There are 1 answers

3
HLP On BEST ANSWER

If I try to keep your logic:

public static ListItem evenElements(ListItem ls) {
    ListItem output = null;

    ListItem current = ls;

    // While the next item exists
    while (current != null){

        // If it's even
        if (current.number % 2 == 0) {

            // If it's the first time we see an even number, initialize output
            if (output == null) {
                output = current.duplicate();
            }
            // Otherwise append this even number to our list of even numbers
            else {
                output.next = current.duplicate();
                output = output.next;
            }
        }
        // Move the next item
        current = current.next;
    }
    if (output != null) {
        output.next = null;
    }
    return output;
}