javascript - Set 如何与 JavaScript 中的单链表中的 Get 配合使用?
问题描述
我是 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
方面。请帮忙!提前致谢
解决方案
因为您没有返回值,所以您返回的是对该值的引用。单链表的整个概念基于引用。
作为一个实验,尝试返回一个新节点。
return new Node(current.val)
它不会执行相同的操作。这个概念在更深层次上称为 a pointer
。
推荐阅读
- javascript - 使用快乐的 ESLint 运行一次 useEffect
- c - 让 C 宏将自己替换为结果中的函数调用?
- java - Amazon 数据管道失败 - 内容长度分隔正文过早结束
- python - 熊猫指数移动平均线(ewm)权重在整个数据系列中“持续存在”?
- python - 澄清批量标准化如何在 Tensorflow 上工作
- c# - 返回 IQueryable
与异步 - reactjs - 单元测试访问全局存储的 React 组件
- r - 如何将一个非常大的文件导入 R(用逗号分隔)
- javascript - TypeScript 和 Axios 响应类型
- git - 致命的:太多的论点。PowerPoint 改变了我的 git 命令