javascript - Javascript 中所有 LinkedList 节点的正确迭代

标签 javascript

<分区>

在我的代码片段中,我使用 while 循环迭代 LinkedList 节点,我在 console.logging 每个节点值。我的 while 循环存在并且我的最后一个值必须是 while 循环之后的下一行 console.logged,无论如何要为我的 LinkedList 创建一个更优雅的迭代器?

function LinkedList() {
    this.head = null;
};

LinkedList.prototype = (function () {
    function reverseAll(current, prev) {
        if (!current.next) { //we have the head
            this.head = current;
            this.head.next = prev;
        }

        var next = current.next;
        current.next = prev;

        reverseAll(next, current);
    };

    return {
        constructor: LinkedList,

        reverse: function () {
            reverseAll(this.head, null);
        },

        head: function() {
            return this.head;
        }
    }
})();

LinkedList.prototype.add = function(value) {
    var node = {
        value: value,
        next: null
    };

    var current;

    if (this.head === null) {
        this.head = node;
    } else {
        current = this.head;
        while (current.next) {
            current = current.next;
        }
        current.next = node;
    }

    return node;
}

LinkedList.prototype.remove = function(node) {
    var current, value = node.value;

    if (this.head !== null) {
        if (this.head === node) {
            this.head = this.head.next;
            node.next = null;
            return value;
        }
        //find node if node not head
        current = this.head;
        while (current.next) {
            if (current.next === node) {
                current.next = node.next;
                return value;
            }

            current = current.next;
        }
    }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$(function() {
    var obj = new LinkedList();
    
    for (var i = 1; i <= 10; i++) {
        obj.add(i);
    }

    var current = JSON.parse(JSON.stringify(obj.head));

    while (current.next) {
        console.log(current.value);

        current = current.next;

    }
    //not so hot iteration, printing last value that would be great if printed in the while loop
    console.log(current.value);
});
</script>

最佳答案

只测试对象,而不是它是否链接到下一个对象。

while (current) { // while not null
    console.log(current.value);
    current = current.next; 
}

关于javascript - Javascript 中所有 LinkedList 节点的正确迭代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33334111/

相关文章:

javascript - 滑出内容框,记住最后一个事件框

javascript - 如何递归调用promise函数

javascript - PHP:strtotime 不适用于 file_get_contents

javascript - 将类重构为 React 中的功能组件

javascript - Puppeteer 从 pdf 下载链接获得响应

javascript - FB.Event.subscribe 后删除div

javascript - 在 jquery 中的动态文本框上分配日期选择器

javascript - 如何验证客户端上的 Javascript 没有被更改

javascript - Nodejs Express 从本地目录上传文件

javascript - pugjs (jade 模板) - 删除 block 语句中的换行符