【问题标题】:Recursive method in a Doubly linked list [closed]双向链表中的递归方法
【发布时间】:2016-09-11 22:44:24
【问题描述】:

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

【问题讨论】:

  • 任何迭代方法也可以递归写,但是你在哪方面有问题呢?你写了一个不起作用的递归方法吗?
  • 这里是你需要实现的递归算法的描述:如果i为1则返回当前元素,否则获取当前元素后i-1位置的元素

标签: java recursion methods data-structures linked-list


【解决方案1】:
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);
} 

【讨论】:

    【解决方案2】:

    试试这样的:

    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)
    }
    

    【讨论】:

      猜你喜欢
      • 2017-08-18
      • 1970-01-01
      • 2016-08-01
      • 2014-06-05
      • 1970-01-01
      • 2019-08-09
      • 2015-07-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多