【问题标题】:Inserting into a sorted list recursively递归插入排序列表
【发布时间】:2012-11-17 02:24:29
【问题描述】:

我需要编写一个方法,将项目递归地插入到单链排序列表中。列表的节点类如下所示:

protected class Node<T> {

    protected Node(T data) {
        this.data = data;
    }

    protected T data;
    protected Node<T> next;
}

protected Node<E> head;

}

方法签名是:void insert(E data)。 我可以迭代地做到这一点,但我似乎无法理解如何递归地做到这一点。谁能提供任何见解?

【问题讨论】:

  • @MatthewDean 不是字面上的循环,它必须是递归的。

标签: java recursion nodes insertion sortedlist


【解决方案1】:

假设您应该在列表末尾插入,只需在 this.next 上重复,直到 this.nextnull

public void insert(E data) {
    if (this.next == null) {
        // we're at the end, so actually do the insert
        // if you can do it iteratively, you should already know what to do here
    } else {
        this.next.insert(data);
    }
}

【讨论】:

    【解决方案2】:

    创建一个函数,该函数接受一个起始节点和要插入的数据。

    如果该节点是放置数据的正确位置,只需插入即可。

    如果没有,则递归调用函数尝试下一个节点。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-15
      • 2012-02-29
      • 1970-01-01
      相关资源
      最近更新 更多