我有一个创建链接列表的类,还有一个将节点添加到该列表的函数。我正在尝试在列表中实现更多功能,但我想通过显示整个列表来查看这些功能所做的更改。
这是代码:
function LinkedList() {
var length = 0;
var head = null;
var Node = function(element) {
this.element = element;
this.next = null;
};
this.size = function() {
return length;
};
this.head = function() {
return head;
};
this.add = function(element) {
var node = new Node(element);
if (head === null) {
head = node;
} else {
var currentNode = head;
while (currentNode.next) {
currentNode = currentNode.next;
}
currentNode.next = node;
}
length++;
};
声明 LinkedList 类并使用 class.add(element( 函数添加元素后,如何使用 console.log(( 显示整个列表?
你需要编写 LinkedList 类的toString
方法。请参阅:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/toString
您可以在对象中定义一个toString
的方法prototype
并遍历所有项。
function LinkedList() {
var length = 0;
var head = null;
var Node = function(element) {
this.element = element;
this.next = null;
};
this.size = function() {
return length;
};
this.head = function() {
return head;
};
this.add = function(element) {
var node = new Node(element);
if (head === null) {
head = node;
} else {
var currentNode = head;
while (currentNode.next) {
currentNode = currentNode.next;
}
currentNode.next = node;
}
length++;
};
}
LinkedList.prototype.toString = function() {
let head = this.head();
let result = [];
while(head) {
result.push(head.element);
console.log();
head = head.next;
}
return result.join(", ");
}
let list = new LinkedList();
list.add("test");
list.add("test2");
list.add("test3");
console.log(list.toString());