自制类的递归indexOf()方法

时间:2016-05-02 01:49:50

标签: java recursion

我有一个类List(这里:http://pastebin.com/ZCi3q7LQ)并且必须为它编写一些方法,包括找到指定整数的索引的方法。

索引从零开始,如果指定的整数不在列表中,则方法必须返回-1,该方法必须递归工作并在$ O(n)$ time内运行。

我的问题是,当调用indexOf时,该方法返回-1,这个整数不在非平凡列表中。我已经尝试了几乎所有可能的组合以及在这里阅读一些类似的问题,但他们没有帮助。这就是我所做的:

public int indexOf(int x) {
    return indexOf(x, first);   
}

private static int indexOf(int x, Node n) {
    if (n==null) {
        return -1;
    }
    else if (n.data==x) {
        return 0;
    }
    else return 1+indexOf(x, n.next);
}

如果列表中的x不是,并且列表非空,则返回最后一个元素的索引,这不是预期的。就像我说我完全失去了如何使这项工作,我感谢任何我能得到的帮助。

(如果重要,是的,这是家庭作业。)

2 个答案:

答案 0 :(得分:1)

问题是当它返回堆栈时,始终在返回的值中添加了一个,包括负值。虽然可以很容易地添加一个检查以查看返回是否为-1,但是有一个更简单的解决方案。

public int indexOf(int x) {
    return indexOf(x, first, 0);   
}

private static int indexOf(int x, Node n, int depth) {
    if (n==null) {
        return -1;
    }
    else if (n.data==x) {
        return depth;
    }
    else return indexOf(x, n.next, depth + 1);
}

答案 1 :(得分:0)

试试这个

if (n != null){ //make sure n isn't null

    if (n.data == x) {
        return index;
    else if (n.next == null)//if the next node is null then you've reached the end of the stack without finding a match
         return -1;
    //else recurse and update the index
    index++;
    return indexOf(x, n.next, index + 1)
    }
}
return -1;