【发布时间】: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