返回语句返回半右。 (半解决,可能是一个错误?)

时间:2016-02-04 03:26:34

标签: java return

//finds the exactNode, where node.data = target
private Node findExact(int target) {
    Node init = head;

    if(init == null) {
        return null;
    }

    int index = 0;
    int size = getSize();
    while((index < size) && (init.data != target)) {
        init = init.next;
        index++;

        //returns null if called from main method. However does not
        //return null out of main method (within other methods in the same class)
        if ((index == size - 1) && (init.data != target)) { 
            return null;
        }
    }

    //this if block is needed somehow, to actually return null if findExact() is
    //used in other methods in the same class.
    if(init == null) {
        return null;
    }

    return init;
}

大约一小时前: 如果没有最后一个if-block,从main方法调用该方法将返回null,但是它会返回while循环中最后一个init的地址。

现在: 没有最后的if-block,它工作正常,我有0个线索为什么。
有人可以详细说明吗?我是否想要解决问题 从未发生过,或者是否是一个错误? 如果它是一个bug,那么如何防止呢?

2 个答案:

答案 0 :(得分:0)

这可能不是一个正确的答案,但我担心它会得到太长时间的评论和尽可能好。问题是代码非常混乱。

  • 您似乎正在实施LinkedList,为什么?
  • 当列表为size时,您还需要null来终止什么?
  • if (init == null) {return null;} return init;中的条件可证明是无用的,你为什么要考虑它呢?

考虑类似

的内容
private Node findExact(int target) {
    for (Node init = head; init != null; init = init.next) {
        if (init.data == target) {
            return init;
        }
        if (init.isTail()) {
            return null;
        }
    }
    return null;
}

只需浏览列表,如果找到正确的节点,则返回它,否则返回null。这就是全部。不要添加错误来修复之前添加的错误。

如果你不喜欢for循环,请试试这个

private Node findExact(int target) {
    Node init = head;
    while (init != null && init.data != target) {
        init = init.next;
        if (init == head) { // back to head again
            return null;
        }
    }
    return init;
}

答案 1 :(得分:0)

回答我自己,但更简单的实施:

private Node findExact(int target) {
    Node init = head;
    int index = 0;
    int size = this.getSize();

    while(index < size) {
        if(init.data == target)
            return init;
        init = init.next;
        index++;
    }
    return null;
}