为什么这个javascript add()函数用于链表返回节点?

why does this javascript add () function for a linked list return node?

本文关键字:链表 用于 返回 节点 函数 javascript add 为什么      更新时间:2023-09-26

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

——在第23行,为什么我们返回node,而不是使用'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);

这个SinglyList的作者只是想这样实现它。

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

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