Javascript

时间:2015-10-25 19:30:47

标签: javascript

在我的代码片段中,我使用while循环迭代LinkedList节点,我是console.logging每个节点值。我的while循环存在,我的最后一个值必须是while.循环之后的console.log下一行,无论如何要为我的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>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:5)

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

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