如何在项目列表中找到偶数元素?

时间:2014-11-18 02:47:00

标签: java list listitem

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;
        }
    }

当我运行项目列表的代码时[3,2,6,9],当它只返回[2,6,9]时,它会返回[2,6]。 duplicate方法复制ListItem,length方法确定列表的长度。我该如何解决这个问题?

1 个答案:

答案 0 :(得分:2)

如果我试图保持你的逻辑:

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;
}