首页 > 解决方案 > 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方面。请帮忙!提前致谢

标签: javascriptclasslinked-listsingly-linked-list

解决方案


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

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

return new Node(current.val)

它不会执行相同的操作。这个概念在更深层次上称为 a pointer


推荐阅读