【问题标题】:Prepend function of my recursive list creates an endless list我的递归列表的前置函数创建了一个无限列表
【发布时间】:2019-04-22 11:48:00
【问题描述】:

目前,我正在研究 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


    【解决方案1】:

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

    您最可能想要做的事情:在添加一个整数时,您希望将其复制到下一个并将值设置为新的整数。那将是:

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

    【讨论】:

      【解决方案2】:

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

      【讨论】:

      • 好的,prepend 方法必须在 Vector 类中但在 Node 类之外?
      • Vector 类中的@cid,因为它改变了列表的head。
      【解决方案3】:

      更新:

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

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

      并在 main 中创建一个向量

      Vector<Integer> v1 = new Vector<Integer>(new Integer(1));
      v1.prepend(new Integer(0));
      

      【讨论】:

      • 我不希望该方法返回任何内容。这对我不起作用。
      猜你喜欢
      • 2015-04-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-10
      • 2020-09-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多