gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:02:31 24 4
gpt4 key购买 nike

<分区>

在我的代码片段中,我使用 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>

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com