var MyLinkedList = function(val) {
this.head = {
val: val,
next: null
};
this.length = 1;
};
MyLinkedList.prototype.addAtHead = function(value) {
var newNode = {
val: value}
newNode.next = this.head
this.length++
return newNode;
};
var test = new MyLinkedList(3);
var test2 = test.addAtHead(12);
var test3 = test2.addAtHead(4)
前两个测试对我有用,但是当我尝试在test3中向头部添加另一个节点时会发生错误:“TypeError:test2.addAtHead不是函数”。我不知道是什么问题。
答案 0 :(得分:0)
通过返回this
并将head
指向newNode
var MyLinkedList = function(val) {
this.head = {
val: val,
next: null
};
this.length = 1;
};
MyLinkedList.prototype.addAtHead = function(value) {
var newNode = {
val: value,
}
newNode.next = this.head;
this.head = newNode;
this.length++;
return this;
};
var test = new MyLinkedList(3);
console.log(test);
var test2 = test.addAtHead(12);
console.log(test2);
var test3 = test2.addAtHead(4);
console.log(test3);

答案 1 :(得分:0)
在addAtHead()
中,您无法创建MyLinkedList
的实例,只需创建具有类似属性的对象即可。您需要实际创建它的实例,以便它具有该方法。
我认为你的一般方法可能有点偏差。您需要列表中的每个链接都是MyLinkedList
的实例。看起来你可能正在创建更类似于数组的东西。
创建链接列表有两种方法。首先,列表中的每个链接都是相同的,您只需直接跟踪头部和当前:
function LinkedList(value) {
return { value, next: null };
}
const head = new LinkedList(5);
head.next = LinkedList(8);
head.next.next = LinkedList(3);
let current = head;
while (current) {
console.log(current.value);
current = current.next;
}

如果你想把它包装成管理跟踪内容的东西,你需要第二堂课:
function LinkedListNode(value) {
return { value, next: null };
}
function LinkedList(firstValue) {
this.head = new LinkedListNode(firstValue);
this.current = this.head;
this.tail = this.current;
this.length = 1;
}
LinkedList.prototype.add = function(val) {
this.tail.next = new LinkedListNode(val);
this.tail = this.tail.next;
this.length++;
};
LinkedList.prototype.rewind = function() { this.current = this.head; }
LinkedList.prototype.next = function() { this.current = this.current.next; }
const linkedList = new LinkedList(5);
linkedList.add(3);
linkedList.add(5);
linkedList.add(8);
while(linkedList.current) {
console.log(linkedList.current.value);
linkedList.next();
}

如果你想在头部添加一些内容,那么你需要将之前的head.next
作为next
添加到新元素:
function LinkedListNode(value) {
return { value, next: null };
}
function LinkedList(firstValue) {
this.head = new LinkedListNode(firstValue);
this.current = this.head;
this.tail = this.current;
this.length = 1;
}
LinkedList.prototype.add = function(val) {
this.tail.next = new LinkedListNode(val);
this.tail = this.tail.next;
this.length++;
};
LinkedList.prototype.rewind = function() { this.current = this.head; }
LinkedList.prototype.next = function() { this.current = this.current.next; }
LinkedList.prototype.insertAtHead = function(val) {
const newNode = new LinkedListNode(val);
newNode.next = this.head.next;
this.head.next = newNode;
}
const linkedList = new LinkedList(1);
linkedList.insertAtHead(2);
linkedList.insertAtHead(3);
linkedList.insertAtHead(4);
while(linkedList.current) {
console.log(linkedList.current.value);
linkedList.next();
}

注意除了第一个值之外,使用该函数的所有值都是向后的(这就是为什么有一个名为addAtHead
的函数有点奇怪。