【问题标题】:Implemented Linked List Constructor to Fill Values to a Certain Size实现链表构造函数以将值填充到特定大小
【发布时间】:2020-03-11 05:28:46
【问题描述】:

我有一个链表类和一个节点类,我想编写一个构造函数,它将用相同的节点填充一个链表,直到大小为“n”。但是,我似乎无法正确地制定逻辑。这是我所在的位置:

我有字段'head'来表示链表的头部。

“节点”类有一个表示下一个值的字段(考虑:node.next)。

    public LinkedList(int size, Object value)
    {
        int index = 0;
        head = value; //setting first node to value
        Object workingReference = head; //creating a working reference to iterate through the list
        for(index = 0; index < size - 1; index++)
        {
            workingReference.next = value; //setting the next node to the given value
            workingReference = workingReference.next; //setting the "index" to the next "index"
        }
    }

问题是循环遇到约束时永远不会有“空”值,因此下一个节点始终是给定的“值”,使得列表“无限”。我玩过将 value.next 设置为 null,但出于某种原因将 head.next 设置为 null。我觉得解决方案就在我面前,但我没有以正确的方式思考它。感谢您的宝贵时间。

【问题讨论】:

    标签: data-structures constructor linked-list


    【解决方案1】:

    首先,将valueworkingReference的类型改为Node而不是Object,以帮助大家理解。

    您的主要问题是您在分配 value 时没有复制它。您可能想要的是 value 变量的值,这就是为什么在这里将其称为 Node 而不是 Object 非常有用。

    public LinkedList(int size, Node value)
    {
        int index = 0;
        head = value; 
        Node workingReference = head;
        for(index = 0; index < size - 1; index++)
        {
            // Here, workingReference, head and value are all the same thing
            // So when you set workingReference.next = value,
            // You've created a loop (value.next points to value)
            workingReference.next = value; 
            workingReference = workingReference.next;         
        }
    }
    

    您要做的是每次都创建一个新节点,其中包含value 节点的内容。让我们将 value 重命名为 initialNode 以更清楚地了解修复的工作原理:

    public LinkedList(int size, Node initialNode)
    {
        int index = 0;
        head = initialNode; 
        Node workingReference = head;
        for(index = 0; index < size - 1; index++)
        {
            Node newNode = new Node(initialNode.value);
            workingReference.next = newNode; 
            workingReference = workingReference.next;         
        }
    }
    

    现在,每个节点都是新的,而不是创建循环。 head 指向initialNode,它的next(以及size 迭代的所有nexts)都指向initialNodevalue 字段。

    如果您希望值 Object 成为传递给方法的东西,请这样做:

    public LinkedList(int size, Object initialValue)
    {
        int index = 0;
        head = new Node(initialValue); 
        Node workingReference = head;
        for(index = 0; index < size - 1; index++)
        {
            Node newNode = new Node(initialValue);
            workingReference.next = newNode; 
            workingReference = workingReference.next;         
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-29
      • 2015-03-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多