我是 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方法,我们返回一个current节点。然后我们在set方法中改变它。但是是否getIndex只返回该节点的值?getIndex那么,为什么我们可以在从(in )更改返回的节点时更改整个列表set?
对不起我的愚蠢问题。随意调整我的知识,特别是class方面。请帮忙!提前致谢
慕慕森
相关分类