简体   繁体   English

自制类的递归indexOf()方法

[英]Recursive indexOf() method for self-made class

I am given a class List (here: http://pastebin.com/ZCi3q7LQ ) and have to write some methods for it, including a method that finds the index for a specified integer. 我得到了一个类List(在这里: http : //pastebin.com/ZCi3q7LQ ),并且必须为其编写一些方法,包括为指定整数查找索引的方法。

Indices start at zero, the method must return -1 if the specified integer is not in the list, the method must work recursively and run in $O(n)$ time. 索引从零开始,如果指定的整数不在列表中,则该方法必须返回-1,该方法必须递归工作并在$ O(n)$时间内运行。

My problem is making the method return -1 when calling indexOf for an integer that's not in the nontrivial list. 我的问题是,当为非平凡列表中的整数调用indexOf时,该方法返回-1。 I've tried just about every possible combination as well as read some similar looking questions here but they didn't help. 我已经尝试了几乎所有可能的组合,并在此处阅读了一些看起来相似的问题,但它们没有帮助。 This is what I made: 这就是我所做的:

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

If x isn't in the list and the list is nonempty this will return the index of the last element, which was not intended. 如果x不在列表中,并且列表为非空,这将返回最后一个元素的索引,这不是预期的。 Like I said I'm at a complete loss how to make this work, I'd appreciate any help I can get. 就像我说的那样,我完全不知道如何进行这项工作,我很感激能得到的任何帮助。

(If it matters, yes this is homework.) (如果重要,是的,这是家庭作业。)

The problem was when it returned back up the stack it always added one to the returned value, including negative one. 问题是,当它返回备份堆栈时, 总是向返回值添加1,包括负1。 While it would be easy to add a check to see if the return is -1 there is an easier solution. 虽然添加支票以查看收益是否为-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);
}

Try this 尝试这个

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM