我的递归列表的前置函数创建了一个无穷无尽的列表

问题描述 投票:0回答:3

目前,我正在研究Java中的通用列表。问题:prepend方法不能正常工作。而不是在索引0处添加元素T,而是创建无限递归列表。

public class Vector<T>{

    private T value;
    private Vector<T> next = null;

    public Vector(T value){
        this.value = value;
    }

    public Vector(T value, Vector<T> next){
        this.value = value;
        this.next = next;
    }

    public void prepend(T element){
        this.next = this;
        this.value = element;
    }
}



public class Main{
    ...
    Vector<Integer> v1 = new Vector<Integer>(new Integer(1));
    v1.prepend(new Integer(0));
    ...

预期输出:{0,1}实际输出:{0,0,0,0,0,0,0,........}

java list generics recursion generic-list
3个回答
0
投票

你在做什么:首先,你创建一个值为1的向量,next = null。 “Prepending”0,你设置旁边,一个无休止的递归,然后你设置value = 0.如果你看看你的Vector,你首先得到值= 0.然后你改变为Vector next,这仍然是这个。在那个“新”矢量中,你输出值= 0.然后你改变为Vector next,这仍然是这个。在那个“新”矢量中,你输出值= 0.然后......你得到它。

您最想要做的事情:在添加Integer时,您希望将其复制到next并将值设置为新的Integer。那会是:

public class Vector<T>{

[…]
    public void prepend(T element){
        this.next = new Vector<>(value, next); // a Copy Constructor would also be fine
        this.value = element;
    }
}

0
投票

this.next = this创建单个元素的循环列表。

您正在尝试使用相同的类实现列表和列表的节点。您应该使用一个类来表示列表(并保持对列表头部的引用),并使用另一个类来表示列表的节点。

您的prepend方法应该创建一个新的链接实例。然后,新实例应成为列表的新头部,其下一个应该是列表的原始头部。

public class Vector<T>{

    public static class Node<T> {
        private T value;
        private Node<T> next = null;
        ...
    }

    private Node<T> head;
    ...
}

0
投票

更新 :

你的prepend方法是错误的。如果您不想保存列表的头部,则您的方法应该是这样的。

public void prepend(T element){
    Vector<T> val = new Vector<T>(element);
    val.next = this.next;
    this.next = val; // after this statement new Element at inserted at 1 position. 
    // Swap the values
    val.value = this.value;
    this.value = element;
}

并在主要创建一个矢量

Vector<Integer> v1 = new Vector<Integer>(new Integer(1));
v1.prepend(new Integer(0));
© www.soinside.com 2019 - 2024. All rights reserved.