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