java - 双向链表中的递归方法

标签 java recursion methods data-structures linked-list

我需要在双向链表中开发一个递归方法(不能使用 while、do ... while 和 for),如果 i 则返回列表的第 i 个元素>= 0 并且i 小于列表的值。否则返回null。任何帮助将非常感激。 这也是我的迭代方法:

public String get(int i) {
    if(i<0 || i>=lenght) {
        return null;
    }
    Node t = head;
    for(int c = 0; c != i; c++) {
       t = t.next;
    }
    return t.element;
}

最佳答案

public String get(Node current, int currentIndex, int targetIndex) {
    // first check the exit condition of the method
    if(currentIndex <0 || currentIndex >= length || current == null) {
            return null;
    }
    // check the second exit contidion
    if (currentIndex == targetIndex)
    {
        return current.element;
    }
    // go forward by increasing the index
    return get(current.next, currentIndex + 1, targetIndex);
} 

关于java - 双向链表中的递归方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39441369/

相关文章:

C#:函数中的函数可能吗?

java - Lotus Notes API 在文档集合合并中给出错误

java - Anylogic新分支抛出 "cannot be resolved to a variable"错误

java - 如何使用递归函数代替嵌套循环?

python - 使用Python递归替换字符串中的字符

java - 从主文件格式调用方法(构造函数)

Java在组件和框架之间添加空间

java - 查询参数长度限制

Ruby 递归不起作用?

java - 为什么方法没有像我想象的那样起作用?