以递归方式构建链接对象列表

时间:2017-06-01 18:54:02

标签: java recursion

我有一个Foo对象,其中有一个引用Bar个对象列表的字段。 Bar列表中的每个Bar对象都引用下一个Foo对象。我们的想法是拥有一个Foo个对象列表,每个对象都有一个Bar列表,指向列表中不同的Foo个对象(即foo1指向foo2 {1}}和foo5)。最后一个Foo对象指向null。在下面的示例中,有两个Foo个实例:foo1指向foo2foo2指向null

如果我想构建一个链接的Foo对象列表,我必须从最后一个对象开始并反向构建它。我可以递归地做这件事吗?

public class Foo {

    private final String id;
    private final List<Bar> barList;

    public Foo(String id, List<Bar> barList) {
        this.id = id;
        this.barList = barList;
    }

    public String getId() {
        return id;
    }

    public List<Bar> getBarList() {
        return barList;
    }
}

public class Bar {

    private final Foo nextFoo;

    public Bar(Foo nextFoo) {
        this.nextFoo = nextFoo;
    }

    public Foo getNextFoo() {
        return nextFoo;
    }
}

public class FooListBuilder {

    public static void main(String[] args) {
        buildFoosInReverse();
        // buildFoosRecursively();
    }

    public static void buildFoosInReverse() {
        List<Foo> fooList = new ArrayList<Foo>();

        Bar bar2 = new Bar(null);
        List<Bar> bar2List = new ArrayList<Bar>();
        bar2List.add(bar2);     
        Foo foo2 = new Foo("2", bar2List);

        Bar bar1 = new Bar(foo2);
        List<Bar> bar1List = new ArrayList<Bar>();
        bar1List.add(bar1);         
        Foo foo1 = new Foo("1", bar1List);

        fooList.add(foo1);
        fooList.add(foo2);      

        System.out.println(fooList);
    }
}

2 个答案:

答案 0 :(得分:1)

首先,代码中的fooList使用的是ArrayListLinkedList不是LinkedList,如果您希望LinkedList可以使用现有的实现:{{3} }。

您可以使用以下内容从ArrayList创建List<Foo> myLinkedList = new LinkedList<Foo>( fooList );

x_0 y_0 1 A = x_1 y_1 1 ... x_n y_n 1

现在回到你的问题,我不知道你怎么能&#34;构建&#34;使用递归的链接列表。

递归有助于解决打印链表等问题 - 即链表已存在时。

如果要构建链接列表,则需要按顺序调用LinkedList

答案 1 :(得分:1)

所以这有点棘手,因为你需要弄清楚什么时候需要实例化,并跟踪什么引用什么。诀窍是你需要在兔子洞里建造你的Foos,然后在回来的路上添加吧。

这是执行此操作的递归代码。

public static List<Foo> buildFoosRecursive(String[] values) {
    ArrayList<Foo> list = new ArrayList<Foo>(values.length);
    buildFoosRecursive(values, 0, list);
    return list;
}

private static void buildFoosRecursive(String[] values, int index, List<Foo> fooList) {
    if (index >= values.length)
        return;

    List<Bar> bar1List = new ArrayList<Bar>(1);
    Foo newFoo = new Foo(values[index], bar1List);
    fooList.add(newFoo);

    buildFoosRecursive(values, index + 1, fooList);

    Bar bar1;
    if (fooList.size() > index + 1)
        bar1 = new Bar(fooList.get(index + 1));
    else
        bar1 = new Bar(null);

    bar1List.add(bar1);

    return;
}
相关问题