我需要开发一个递归方法(不能使用while, do…如果i>>= 0且i小于链表的值,则返回链表的第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);
}
试试这样:
public String get(int i) {
if(i<0 || i>=lenght) return null;
return iter(head, i)
}
public String iter(Node t,int i){
if(t == null) return null;
if(i == 0) return t.elemnt;
return iter(t.next, i - 1)
}