我是 JavaScript 新手,正在尝试学习数据结构和算法。
我正在努力理解 set
如何通过依赖 getIndex
来工作。
代码如下:
class Node{
constructor(val){
this.val = val;
this.next = null
}
}
class SinglyLinkedList{
constructor(){
this.head = null;
this.tail = null;
this.length = 0;
}
push(val){
let newNode = new Node(val);
if(!this.head){
this.head = newNode
this.tail = this.head
}else{
this.tail.next = newNode;
this.tail = newNode
}
this.length++;
return this;
}
getIndex(index){
if(index > this.length || index < 0) return null;
let counter = 0, current = this.head;
while(counter !== index){
current = current.next;
counter++;
}
return current; // Here we return a value of the node we found
}
set(val, index){
let foundNode = this.getIndex(index);
if(foundNode){
foundNode.val = val;
// We can change the value of the node we founded in getIndex. Then the set works
// I don't understand why we can do this.
// Since what we do in getIndex is just returning a value of the node.
// How does changing that returned node can change the context of the list in term of the purpose of set
return true;
}
return false;
}
}
let list = new SinglyLinkedList();
list.push(88);
list.push(33);
list.push(11)
list.getIndex(1) // Output: Node: {val: 33, next: 11}. Why does changing this returned node can change the context of the whole list?
list.set(77,1) // Output: true. List (new) : 88 -> 77 -> 11
基本上,我关心的是在 getIndex
方法中,我们返回一个当前
节点。然后我们在set
方法中更改它。但是 getIndex
是否只返回该节点的值?那么,为什么我们在更改从 getIndex
(在 set
中)返回的节点时可以更改整个列表呢?
抱歉我的问题很愚蠢。请随意调整我的知识,特别是class
方面。请帮忙!提前致谢
最佳答案
因为您没有返回该值,所以您正在返回对该值的引用。单链表的整个概念是基于引用的。
作为实验,尝试返回一个新节点。
return new Node(current.val)
它不会执行相同的操作。这个概念在更深层次上称为指针
。
关于javascript - JavaScript 中的单链表中的 Set 如何与 Get 一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61493497/