gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 03:22:20 24 4
gpt4 key购买 nike

我需要在双向链表中开发一个递归方法(不能使用 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com