Java中的递归和LinkedList

Sno*_*man 1 java string recursion linked-list

好的说我有一个函数可以在自定义LinkedList类中查找特定的单词:

public LinkedList find(String word) {
    if (this.word.equals(word))
        return this;
    if (next==null)
        return null;
    if (next.find(word)==next)
        return next;
    return null;
}
Run Code Online (Sandbox Code Playgroud)

此代码工作正常,但它返回匹配条件的FIRST找到的对象.如果我想返回与参数匹配的LAST对象怎么办?我很难搞清楚这一点.请记住我想使用递归.

编辑:这段代码会出现什么问题:

public LinkedList findLast(String word) {
    LinkedList temp=new LinkedList(word, null);
    if (next==null && next.word.equals(word))
        return next;
    if (next==null && !next.word.equals(word))
        temp=next.findLast(word);
    return temp;
}
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 8

嗯,认为它是这样的:你需要递归到列表的末尾,然后让返回值泡沫了.

所以你的方法的开始应该是一个递归调用,以查看列表的下方,或者注意到我们位于列表的末尾 - 这相当于"进一步"结果为null.

现在当你回来时,有三种选择:

  • 你已经找到了比当前点更晚的匹配 - 所以返回该引用
  • 没有找到匹配项(因此递归调用的返回值为null)和:
    • 当前点的单词匹配 - 因此返回当前点
    • 当前点不匹配 - 因此返回null

希望这应该足以让你实现 - 如果没有,请提出更多问题.当这可能是家庭作业时,我宁愿不完全实施.