【问题标题】:Incrementing an integer in a recursive method doesn't work(LinkedList)在递归方法中递增整数不起作用(LinkedList)
【发布时间】:2017-01-07 23:28:20
【问题描述】:

基本上我不知道为什么我的整数 n 没有变高。
感谢您的每一个回答!

    public int n;

    public int firstIndexOf(T val) {
    if (val == this.getValue()) {
        return n;
    } else {
        if (val != this.getValue() && this.next != null) {
            n++;
            return this.next.firstIndexOf(val);

        } else {
            return -1;
        }
    }
   }

【问题讨论】:

  • 我认为这是Java?您应该在问题中包含此类详细信息。
  • 因为您要查找的元素总是在第一个节点找到,或者列表只有一个元素。 NB 1. 这是糟糕的编程。首先,不是线程安全的。您应该将 n 的新值作为参数传递。 2. 你不需要第一个!= 测试。你已经在一个else 中这么说。 3. 您应该将值与equals() 进行比较,而不是==。
  • 好的,谢谢!问题是,是学生任务的一部分,我在java中很新,这就是为什么它的问题很糟糕。是的,你的权利,我可以删除第一个!= 谢谢。我不允许添加参数。你有解决办法吗?否则我可以用非递归方法来实现。编辑:我想我有一个想法,我制作了另一种复制 val 并具有参数 n 的方法。希望它有效!
  • 使其成为非递归的。或者,如果您可以添加第二个内部方法,该方法采用参数并进行递归。

标签: java recursion increment


【解决方案1】:

增量(n++)在错误的条件检查中:

    private int n = 0;

    public int firstIndexOf(int val) {
        if ( val == this.getValue() ) {
            return n+1; //This is were the increment should happen
        }
        else {
            if ( this.next != null ) {
                return this.next.firstIndexOf(val);
            } else {
                return -1;
            }
        }
    }

另外,如果你想计算你的链表中与 val 具有相同值的所有元素,你可以使用这个:

private int n = 0;

public int firstIndexOf(int val) {
    if ( val == this.getValue() ) {
        if ( this.next != null ) {
            return 1 + this.next.firstIndexOf(val);
        }
        else {
            return 1;
        }
    } else {
        if ( this.next != null ) {
            return this.next.firstIndexOf(val);

        } else {
            return 0;
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-12
    • 1970-01-01
    • 2018-07-14
    • 2020-07-26
    相关资源
    最近更新 更多