Я работаю над пониманием того, как эта реализация с одним списком ссылок работает в JavaScript. В частности, операторы return в строках 23 и 35 в методе add().Почему эта функция javascript add() для связанного списка возвращает узел?
- В строке 23, почему мы должны возвращать узел вместо использования 'return'; вместо? - В строке 35, почему мы должны возвращать узел, если он не влияет на функциональность кода в любом случае?
Спасибо!
// 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);
«Зачем это нужно» - это не _need_, но это там, если вы или кто-то еще захотите эту функцию позже. –
Хорошая точка. Измененная формулировка вопроса. – bobNelson