【发布时间】:2014-09-08 04:45:22
【问题描述】:
我正在尝试在 javascript 中实现循环链表。 我只想知道在javascript中实现这个的正确方法吗? 是否存在内存泄漏或无限对象创建?
function LinkedList() {
this.Node = null;
this.count = 0;
this.head = null;
};
LinkedList.prototype.append = function (value) {
// create new node
var node = this.createNode(value);
console.log(value);
if (this.head == null) {
this.Node = node;
this.Node.next = null;
this.head = this.Node;
} else {
var ptr = this.Node;
while (ptr.next != null) {
ptr = ptr.next;
}
ptr.next = node;
}
this.count++;
};
LinkedList.prototype.getSize = function () {
console.log(this);
};
LinkedList.prototype.close = function () {
var ptr = this.head;
while (ptr.next != null) {
ptr = ptr.next;
}
ptr.next = this.head;
};
LinkedList.prototype.createNode = function (value) {
var node = {};
node.value = value;
node.next = null;
return node;
};
var li = new LinkedList();
li.append(1);
li.append(2);
li.append(3);
li.append(4);
li.close();
li.getSize();
当我检查控制台时,它显示为 head 包含一个节点,并且该节点包含另一个节点等。 它是引用还是它们存储的实际对象?
【问题讨论】:
-
如果您自己没有发现任何错误,您应该询问 codereview。
-
是唯一的特性节点添加吗?
-
我想使用循环链接列表。我不想要 remove , display 等功能。我只想知道对象的数量以及在javascript中实现循环链表的正确方法。
-
将链表数据和方法保存在自己的节点中是否符合 javascript 标准?我是新手,但在 c++ 国际象棋编程中,我通常创建树创建器、树遍历器和节点类.每个节点都有独立的盒子创建填充数据并由树创建者添加到位。遍历由遍历器类管理,该类负责向前向后和分支移动。
标签: javascript linked-list circular-list