E
E
Ed10242015-10-25 22:48:08
JavaScript
Ed1024, 2015-10-25 22:48:08

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

1 answer(s)
A
Alex, 2015-10-25
@Ed1024

In JS, objects are copied by reference, not by value. When you do this:
variables tempand listrefer 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);

Why do you need such a structure? Doesn't fit a regular array?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question