我是 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方面。請幫忙!提前致謝
Set 如何與 JavaScript 中的單鏈表中的 Get 配合使用?
慕虎7371278
2022-07-21 10:07:44