【发布时间】:2018-03-09 22:55:11
【问题描述】:
我正在尝试用 javascript 编写一个链表。我有一个类、一个构造函数和一个 addtoLast 函数,它们提供彼此之间的连接。
但在 addtoLast 函数中,我无法访问任何对象的“next”属性。
上面写着
无法在数字“x”上创建属性“next”
(x 作为第一个值和链表的头)
代码是:
class LinkedList
{
constructor()
{
this.head=[];
this.next=null;
this.length=0;
}
addtoLast(value)
{
if(this.head==null)
{
this.head=value;
this.length++;
}
else
{
let now=this.head;
let newNode=value;
while(now.next!=null)
now=now.next;
now.next=newNode; //it gives that error
newNode.next=null; //and it gives too!
this.length++;
}
}
}
//and my main function is:
let example = new LinkedList();
example.head = 3;
example.addtoLast(9);
document.write(example);
我会感谢任何评论:)
【问题讨论】:
-
let newNode=value;这应该怎么做?而且您似乎不了解链表 -
now is an integer,您不能将next属性分配给整数,如错误所示。相反,将整数包装在节点对象{ value: now, next: ... } -
你声明了
this.head=[],你的列表有多个头? -
newNode 只是值的变量。我们用它来达到下一个值。所以我们不能说
value.next这就是我的意思。 @JonasW。 -
你建议我做那个构造函数必须有“节点部分”@caesay
标签: javascript oop properties linked-list null