0
votes

i am practicing javascript, and i am creating a single linked list like example, but i'm getting at the last node [object] instead of adding a new node to the list.

This is my code right now, i hope you can help me, maybe my mistake is at the addNode method.

 function Node(value) {
  this.value = value;
  this.nextNode = null;
}

Node.prototype.addNode = function(newNode) {
  function append(node) {
    if (node.nextNode == null) {
      node.nextNode = newNode;
    }
    else {
      return append(node.nextNode);
    }
  }
  return append(this);
}

var firstNode = new Node(5);
var node2 = new Node(3);
var node3 = new Node(4);
var node4 = new Node(8);
var node5 = new Node(1);

console.log(firstNode);
firstNode.addNode(node2);
console.log(firstNode);
firstNode.addNode(node3);
console.log(firstNode);
firstNode.addNode(node4);
console.log(firstNode);
firstNode.addNode(node5);
console.log(firstNode);

this was printed with Node.js

Node { value: 5, nextNode: null } Node { value: 5, nextNode: Node { value: 3, nextNode: null } } Node { value: 5, nextNode: Node { value: 3, nextNode: Node { value: 4, nextNode: null } } } Node {
value: 5, nextNode: Node { value: 3, nextNode: Node { value: 4, nextNode: [Object] } } } Node { value: 5, nextNode: Node { value: 3, nextNode: Node { value: 4, nextNode: [Object] } } }

1
The console.log is just shortening it for you. If you navigated into the node a bit deeper it would show nesting a bit deeper. console.log(firstNode.nextNode) - Kevin B
If you want it to spit out the whole thing, you can console.log(JSON.stringify(firstNode, null, 2)); - Dan Crews
Thanks for your answers! @DanCrews JSON.stringify worked like a charm! i was thinking there was a problem when adding, but i doubled checked so, that's why i asked! Thank you very much, makes noobs coders life easier. - jdecuirm

1 Answers

0
votes

Use util.inspect() to investigate the full linked list.

var util = require('util');

console.log(util.inspect(myObject, {showHidden: false, depth: null}));

# alternative shortcut
console.log(util.inspect(myObject, false, null));