java - 如何递归复制列表?

标签 java list recursion methods

这是我的代码:

public class ListItem {

    final int number; //These need to stay this way because I need to access them later
    ListItem next;

    ListItem(int number, ListItem next) {
        this.number = number;
        this.next   = next;
    }

    // I need to return a copy of this list using recursion, not iteration.
    public ListItem duplicate() {
        if (duplicate() == ListItem) { //base case??
            return next;
        }
        else return duplicate(); //just a placeholder
   }

我不确定基本情况应该是什么以及递归调用是什么,因为 duplicate() 不带任何参数。有人可以告诉我 Java 如何看待这些方法吗?我想了解这是如何运作的。

最佳答案

public ListItem duplicate() {
    if (next == null) {
        // base case: last item in the chain
        return new ListItem(this.number, null);
    }
    else {
        // start by duplicating the rest of the chain:
        ListItem newNext = next.duplicate();
        return new ListItem(this.number, newNext);
    }
}

或者,更简洁地说:

public ListItem duplicate() {
    ListItem newNext = next == null ? null : next.duplicate();
    return new ListItem(this.number, newNext);
}

关于java - 如何递归复制列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20020150/

相关文章:

python - 编写更好的代码而不是 2 个 for 循环

c++ - 迭代器如何找到链表中的下一个地址

java - 如何修复: Sudoku solver Stack overflow problem

Java ArrayList 获取方法

java - LinkedHashMap 是在双向链表的帮助下实现的,是否可以用两种方式迭代它?

swift - 如何从SwiftUI的另一个 View 中删除列表的项目?

javascript - 在 JavaScript 中递归维护祖先/ parent 嵌套对象

java - 使用Java解析XML转换为Json

java - JACOB:Presentation.Export:PowerPoint 无法将 ^0 保存到 ^1

C++ 二叉树插入/高度