亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Set 如何與 JavaScript 中的單鏈表中的 Get 配合使用?

Set 如何與 JavaScript 中的單鏈表中的 Get 配合使用?

慕虎7371278 2022-07-21 10:07:44
我是 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方面。請幫忙!提前致謝
查看完整描述

1 回答

?
慕慕森

TA貢獻1856條經驗 獲得超17個贊

因為您沒有返回值,所以您返回的是對該值的引用。單鏈表的整個概念基于引用。

作為一個實驗,嘗試返回一個新節點。

return new Node(current.val)

它不會執行相同的操作。這個概念在更深層次上稱為 a pointer。


查看完整回答
反對 回復 2022-07-21
  • 1 回答
  • 0 關注
  • 89 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號