javascript中的循环链表
我试图用javascript实现循环链表。 我只是想知道用javascript实现这一点是否正确? 是否存在内存泄漏或无限对象创建javascript中的循环链表,javascript,linked-list,circular-list,Javascript,Linked List,Circular List,我试图用javascript实现循环链表。 我只是想知道用javascript实现这一点是否正确? 是否存在内存泄漏或无限对象创建 function LinkedList() { this.Node = null; this.count = 0; this.head = null; }; LinkedList.prototype.append = function (value) { // create new node var node = this.
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包含一个节点,而该节点包含另一个节点等。
是引用还是他们存储的实际对象?我觉得你的附加函数有点缺陷。。。因为就在它执行之后,您的列表处于不一致的状态。您需要调用close()才能正确设置所有内容。我的建议是,您可以修改append()函数,根据需要动态更新head和tail;因此,您不需要调用close() 下面是我如何实现append()方法(基本上只是稍微修改一下代码):
getCircular(开始){
设i=0,j=0;
设secondHead=this.head;
让指针=this.head;
设指针2=第二个磁头;
而(我是尤维->沙玛->达旺,
如果你通过一个2的索引,那么结果如下:
尤维->沙玛->达旺->科利->多尼
那么您的呼叫应该是:ll.getCircular(2);//ll是一个对象,例如如果你自己没有发现任何错误,你应该询问codereview。唯一的功能节点是添加的吗?我想使用循环链接列表。我不想使用删除、显示等函数。我只想知道对象的数量,以及在javascript中实现循环链接列表的正确方法。它与用JavaScript标准来保持链接列表数据和方法在节点中是自己的吗?我对它是新的,但是在C++的象棋编程中,我通常创建一个树创建器,一个树遍历器和一个节点类。每个节点都是独立的盒子,创建的数据填充并由树创建者添加。我同意你的观点,但我不想在我的代码中实现这个功能,因为我最后必须构造链表。我不想在每次插入后更改链接。
LinkedList.prototype.append = function(value) {
var node = {
value: value,
next: this.head
};//cricular node
if (this.count === 0) {
this.head = {};
this.head.value = value;
this.head.next = this.head;
this.tail = this.head;
} else {
this.tail.next = node;
this.tail = node;
}
this.count++;
};
getCircular(start){
let i=0,j=0;
let secondHead = this.head;
let pointer = this.head;
let pointer2 = secondHead;
while(i<start){
let temp1 = pointer.next;
pointer = temp1;
i++;
}
this.head = pointer;
this.tail.next = pointer2;
while(j<start-1){
let temp2 = pointer2.next;
pointer2 = temp2;
j++;
}
this.tail = pointer2;
this.tail.next = null;
return this;
}