我试图理解在JavaScript的单链表实现中传递引用(指针)的概念
我试图用JavaScript实现一个单链表,我很难想象传递引用的概念(以及指向何处的内容)。我的代码在下面,我已经跟进了一些问题或我的理解,请你检查一下,让我知道我的思路是否正确我试图理解在JavaScript的单链表实现中传递引用(指针)的概念,javascript,algorithm,linked-list,Javascript,Algorithm,Linked List,我试图用JavaScript实现一个单链表,我很难想象传递引用的概念(以及指向何处的内容)。我的代码在下面,我已经跟进了一些问题或我的理解,请你检查一下,让我知道我的思路是否正确 class Node{ constructor(val){ this.val = val; this.next = null; } } class LinkedLists { constructor(){ this.head = null;
class Node{
constructor(val){
this.val = val;
this.next = null;
}
}
class LinkedLists {
constructor(){
this.head = null;
this.length = 0;
this.tail = null;
}
// methods
addNodeStart(val){
let node = new Node(val);
if (this.length === 0){
this.length++;
this.head = node;
this.tail = node;
} else {
node.next = this.head;
this.head = node;
this.length++;
}
return this;
}
addNodeEnd(val){
let node = new Node(val);
if (this.length === 0){
this.length++;
this.head = node;
this.tail = node;
} else {
this.length++;
this.tail.next = node;
this.tail = node;
}
}
}
我的理解是:
节点。然后
指向this.head
(this.head指向设置为head的节点)。因此,this.head
只是一个容器,其中包含对节点的引用??或者这是一个实际的节点?然后再次将this.head设置为node。因此,this.head只是一个变量名,例如,让x=5;这里x引用了5的内存位置那么,我是否认为this.head只是一个容器(变量),它保存一个节点的值?还是我错过了一些东西?我不知道你想要实现什么。但这可能有助于调试您的列表: 您可以使用toArray方法,然后在控制台中检查列表
LinkedLists.prototype.toArray = function() {
let = element = this.head
const array = []
while(element) {
array.push(element)
element = element.next || null
}
return array
}