1

I am currently coding in Javascript, I am a newbie and I need help with my code. I want to create a Tree that contains Nodes(obviously) which points to a Linked List, this List will contain Node childs. The only node I need outside a Linked List is my root Node.

Anyways, my problem is with adding a Node to the Linked List of my Father node. Example:

Root -> LinkedList(Node->Node->Node->null) each points to another Linked List.

When I try to add a Node in the Linked List my first node is overwritten.

Code:

var list = new LinkedList();
var rootnode = new Node("Root");
list.add(rootnode, 20);
list.add(rootnode, "Como");
list.add(rootnode, "Estas");
list.add(rootnode, "ggg");
list.print(rootnode);

function LinkedList() {
  this.first = null;
  this.add = LinkedListAdd;
  this.print = LinkedListPrint;
  this.search = LinkedListSearch;
}

function Node(value) {
  this.value = value;
  this.next = null;
  this.child = new LinkedList();
}

function LinkedListAdd(node, item) {
  if (!node.child.first) {
    node.child.first = new Node(item);
  } else {
    while (node.child.first.next) {
      node.child.first = node.child.first.next;
    }
    node.child.first.next = new Node(item);
  }
}

printing my rootnode.child.first gives me: "Estas"

1 Answer 1

1

You should not override node.child.first, instead take a local variable:

    let acc = node.child.first;
    while(acc.next) acc = acc.next;
    acc.next = new Node(item);

Tip: You can access the LinkedList inside LinkedListAdd with this, which allows you to make this possible:

 root.children.add(10);

then you don't need this unnecessary list.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.