【发布时间】:2016-06-11 04:41:46
【问题描述】:
我无法指向最后一个节点。
输出应该是这样的:
具有 5 个节点的链表
节点值:头节点/下一个节点值:第二个节点/最后一个节点值:
null节点值:第二个节点/下一个节点值:第三个节点/最后一个节点值:头节点
节点值:第三个节点/下一个节点值:第四个节点/最后一个节点值:第二个节点
节点值:第四个节点/下一个节点值:尾节点/最后一个节点值:第三个节点
节点值:尾节点/下一个节点值:未定义/最后一个节点值:第四个节点
但是,我不断得到这个:
具有 5 个节点的链表
节点值:头节点/下一个节点值:第二个节点/最后一个节点值:
undefined节点值:第二个节点/下一个节点值:第三个节点/最后一个节点值:
undefined节点值:第三个节点/下一个节点值:第四个节点/最后一个节点值:
undefined节点值:第四个节点/下一个节点值:尾节点/最后一个节点值:
undefined节点值:尾节点/下一个节点值:未定义/最后一个节点值:
null
var DoubleLinkedList = function() {
this.head = 0;
this.tail = 0;
this.length = 5;
var LinkedListNode = function(content) {
this.next = 0;
this.last = [];
this.content = content;
};
this.add = function(content) {
if (this.head == 0) {
this.head = new LinkedListNode(content);
return this.head;
}
if (this.tail == 0) {
this.tail = new LinkedListNode(content);
this.head.next = this.tail;
return this.tail;
};
this.tail.next = new LinkedListNode(content);
this.tail = this.tail.next;
this.tail.next = 0;
return this.tail;
};
}
DoubleLinkedList.prototype.length = function() {
var i = 0;
var node = this.head;
while (node != 0) {
i++;
node = node.next;
}
return i;
};
DoubleLinkedList.prototype.toString = function() {
var i = 1;
var str = 'Linked List with ' + this.length + ' nodes <br/>';
var node = this.head;
while (node != 0) {
str += i + ': Node Value: ' + node.content;
str += ' / Next Node Value: ' + node.next.content;
str += " / Last Node Value: " + node.last;
if (node.next == 0) str += ' null';
if (node.next != 0) str += node.last.content;
i++;
str += "<br>";
node = node.next;
}
return str;
};
var lln = new DoubleLinkedList();
lln.add(' Head Node');
lln.add(' Second Node');
lln.add(' Third Node');
lln.add(' Fourth Node')
lln.add(' Tail Node');
document.getElementById('output').innerHTML = lln.toString();
<p id='output'></p>
【问题讨论】:
-
我知道它可能是一些愚蠢而小的东西,但我已经看了好几个小时了,找不到我做错了什么
-
这里是 jsfiddle 链接 jsfiddle.net/7kd24pf7/11
-
请停止将您键入的所有内容加粗。我已将您的代码移动到可运行的 sn-p 中,以便人们更轻松地诊断问题。
-
没问题,谢谢
标签: javascript node.js