Answer the question
In order to leave comments, you need to log in
Singly linked list, how to add elements?
How to add elements to a singly linked loop?
var printList = function(list){
var tmp = list;
for(var i = 0; i < 3; i++){
console.log(tmp.value);
tmp = tmp.rest;
}
}
var list = {
value: 1,
rest: null
}
/* Не работает, добавляет последний элемент с выводом - 2
2
2
{ value: 2, rest: [Circular] }
*/
var temp = list;
for(var i = 0; i < 3; i++){
temp.value = i;
list.rest = temp;
temp = list.rest;
}
printList(list);
console.log(list);
Answer the question
In order to leave comments, you need to log in
In JS, objects are copied by reference, not by value. When you do this:
variables temp
and list
refer to the same object. So
the same as
You probably want something like this:
function printList(list){
var tmp = list;
while (tmp.rest !== null) {
console.log(tmp.value);
tmp = tmp.rest;
}
}
var list = {
value: 1,
rest: null
};
for(var i = 0; i < 10; i++){
temp = { value: i, rest: list };
list = temp;
}
printList(list);
console.log(list);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question