我是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
(在set
中)更改返回的节点时,为什么还要更改整个列表?
对不起,我这个愚蠢的问题。随时调整我的知识,特别是class
方面。请帮忙!在此先感谢
因为您没有返回值,所以您正在返回对该值的引用。单链接列表的整个概念都基于引用。
作为实验,请尝试返回一个新节点。
return new Node(current.val)
它不会执行相同的操作。这个概念在更深层次上称为pointer
。