为什么这个javascript对一个链表return节点的add()函数呢?
why does this javascript add () function for a linked list return node?
我正在努力了解这个单链表实现在 JavaScript 中的工作原理。具体来说,add() 方法中第 23 行和第 35 行的 return 语句。
-- 在第23行,为什么我们要return节点,而不是使用'return';反而?
-- 在第 35 行,为什么我们 return 节点似乎不会以任何方式影响代码的功能?
谢谢!
// Constructors (Node and SinglyList)
function Node(data) {
this.data = data;
this.next = null;
}
function SinglyList() {
this._length = 0;
this.head = null;
}
//Add Method
SinglyList.prototype.add = function(value) {
var node = new Node(value),
currentNode = this.head;
if(!currentNode) {
this.head = node;
this._length++;
// return the new Node object. (why can't we just use return; here?)
return node;
}
//USE CASE 2: NON-EMPTY LIST
while (currentNode.next) {
currentNode = currentNode.next;
}
currentNode.next = node;
this._length++;
// return statement doesn't seem to do anything here.
return node;
};
var list = new SinglyList();
list.add(1);
list.add(2);
list.add('foo');
console.log(list.head);
这个 SinglyList 的作者只是想那样实现它。
在用户想要引用列表中创建的新节点的用例中,他们可以保存它而不是在添加后再次找到该节点。没有单一的正确 方式来实现 LinkedList,还有很多需要解释的地方。
如果添加节点后不需要引用,可以选择忽略返回的元素。
我正在努力了解这个单链表实现在 JavaScript 中的工作原理。具体来说,add() 方法中第 23 行和第 35 行的 return 语句。
-- 在第23行,为什么我们要return节点,而不是使用'return';反而? -- 在第 35 行,为什么我们 return 节点似乎不会以任何方式影响代码的功能?
谢谢!
// Constructors (Node and SinglyList)
function Node(data) {
this.data = data;
this.next = null;
}
function SinglyList() {
this._length = 0;
this.head = null;
}
//Add Method
SinglyList.prototype.add = function(value) {
var node = new Node(value),
currentNode = this.head;
if(!currentNode) {
this.head = node;
this._length++;
// return the new Node object. (why can't we just use return; here?)
return node;
}
//USE CASE 2: NON-EMPTY LIST
while (currentNode.next) {
currentNode = currentNode.next;
}
currentNode.next = node;
this._length++;
// return statement doesn't seem to do anything here.
return node;
};
var list = new SinglyList();
list.add(1);
list.add(2);
list.add('foo');
console.log(list.head);
这个 SinglyList 的作者只是想那样实现它。
在用户想要引用列表中创建的新节点的用例中,他们可以保存它而不是在添加后再次找到该节点。没有单一的正确 方式来实现 LinkedList,还有很多需要解释的地方。
如果添加节点后不需要引用,可以选择忽略返回的元素。