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

How does Set work with Get in Singly Linked List in JavaScript?

我是 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 方法,我们 return 一个 current 节点。然后我们在 set 方法中更改它。但是 getIndex 只是 return 那个节点的值吗?那么,为什么我们可以在从 getIndex(在 set 中)更改 returned 节点时更改整个列表?

抱歉我的愚蠢问题。随意调整我的知识,特别是 class 方面。请帮忙!提前致谢

因为您没有 return 值,所以您 return 是对值的引用。单链表的整个概念都是基于引用的。

作为实验,尝试 return 一个新节点。

return new Node(current.val)

它不会执行相同的操作。这个更深层次的概念叫做pointer.