javascript - JavaScript 中的单链表中的 Set 如何与 Get 一起使用?

标签 javascript class linked-list singly-linked-list

我是 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/

相关文章:

c++ - 搜索链表,不同的数据类型

javascript - selenium 和 Protractor 崩溃,无法截图

javascript - 在 dc js 中创建堆叠条形图

Python:使用 locals() 进行编程类实例变量初始化

java - Java中的多个线程导致问题

c++ - 测试链表是否相等

c - 通过排序在链表中插入新元素 C

javascript - 选择的 ng-options 不使用对象作为模型 [Angular 1.5]

javascript - 使用 ES6 过滤带有数组的对象

c# - 如何在 C# 中通过所有者控制类可见性