【问题标题】:why does this javascript add () function for a linked list return node?为什么这个 javascript add() 函数为链表返回节点?
【发布时间】:2015-10-11 18:32:22
【问题描述】:

我正在努力了解这种单链表实现在 JavaScript 中的工作原理。具体来说,就是 add() 方法中第 23 行和第 35 行的 return 语句。

-- 在第 23 行,为什么我们要返回节点,而不是使用 'return';反而? -- 在第 35 行,为什么我们要返回 node,因为它似乎不会影响代码的功能?

谢谢!

    // Constructors (Node and SinglyList)
    function Node(data) {
        this.data = data;
        this.next = null;
    }

    function SinglyList() {
        this._length = 0;
        this.head = null;
    }

    //Add Method

    SinglyList.prototype.add = function(value) {
        var node = new Node(value),
            currentNode = this.head;

        if(!currentNode) {
            this.head = node;
            this._length++;

            // return the new Node object. (why can't we just use return; here?)
            return node;
        }

        //USE CASE 2: NON-EMPTY LIST
        while (currentNode.next) {
            currentNode = currentNode.next; 
        }
        currentNode.next = node;

        this._length++;

        // return statement doesn't seem to do anything here.
        return node;
    };

    var list = new SinglyList();
    list.add(1);
    list.add(2);
    list.add('foo');
    console.log(list.head);

【问题讨论】:

  • '为什么需要' - 它不需要需要,但如果您或其他人以后想要该功能,它就在那里。
  • 好点。更改了问题的措辞。

标签: javascript linked-list


【解决方案1】:

这个 SinglyList 的作者只是想以这种方式实现它。

在用户想要对列表中创建的新节点的引用的用例中,他们可以保存它,而不是在添加后再次找到该节点。没有单一的正确方式来实现 LinkedList,还有很多需要解释。

如果添加节点后不想引用,可以选择忽略返回的元素。

【讨论】:

    猜你喜欢
    • 2019-04-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-21
    • 2018-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多