-1

所以这里有一些代码,我对正在发生的事情有基本的逻辑,但我想逐行了解它在做什么。我找不到类似于 Python 导师的 Javascript 代码检查,所以请帮助我。我想逐步了解 LinkedLists 是如何工作的以及这段代码在做什么。我们什么时候会在实际示例中使用它?这个数组有什么区别?

4

3 回答 3

1

基础知识:

链表是由节点组成的数据结构。每个节点都保存一些有用的数据和对下一个节点的引用。要保留对列表的引用,您只需保留对第一个节点的引用。该列表以一个节点结束,该节点具有对 null 的引用,而不是另一个节点。

JS代码(注释):

// node structure:
//{ data: value, // useful data
// next: nextNode } // reference to next node. null for last node


var LinkedList = function() { // constructor function
     this.head = null; // reference to the first node
};

LinkedList.prototype.insert = function(value) { // function you use to insert a new node
     if(this.head === null) { // code for when the list has no nodes.
         this.head = {data: value, next: null}; // simply init the reference to the first node to a node
     } else { // if there are nodes, you need to go through the list to get the to the last node
         var temp = this.head; // start from the first node
         while(temp.next !== null) { // until you find the node that has no next
             temp = temp.next; // go from one node to the next
         }
         temp.next = {data: value, next: null}; // the last node should point to a new node you create (which points to nothing, so it becomes the last node)
     } };

更好的解决方案:

在列表结构中也保留指向最后一个节点的指针。插入变为 O(1)。删除仍然是O(n),如果最后一个节点被删除,则需要更新指针。

编辑:回答您的新问题

通常数组更好,但在某些情况下链表更可取。一个明显的例子是在具有大量碎片内存的环境中。数组需要连续分配的内存,所以如果内存是碎片的,你可以分配的最大数组非常小。只要还有一个节点的空间,链表总是可以在任何地方获得更多的内存。我还没有遇到过链表在 JS 中有用的情况(也许是面试问题?),但有趣的是知道它可以做到。

于 2013-11-09T20:56:52.937 回答
1

您可以使用诸如 firebug 或 chrome 开发工具之类的东西,设置断点并逐步进入代码

于 2013-11-09T20:59:38.560 回答
0

我相信您是在询问有关在 javascript 中进行测试的问题。您可能想查看JasmineQUnit。我对python导师不熟悉,所以我不知道这些是否相似,但这是一个开始。

于 2013-11-09T20:52:59.780 回答