如何递归复制List?

时间:2013-11-16 15:27:23

标签: 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如何看待这些方法吗?我想知道它是如何工作的。

1 个答案:

答案 0 :(得分:1)

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