Bugging Pointers

So I have this object, a Node, that has pointers (left_, right_)to other nodes.
I also have this code that takes the "smallest" 2 nodes from a heap and combines them as children of a third node, then inserts the new node.
1
2
3
4
5
6
7
8
while (heap.size() > 1)
  {
    Node<char, long> n1 = pop_element(heap);
    Node<char, long> n2 = pop_element(heap);
    Node<char, long> n(n1, n2);
    insert(heap, n);
    cout << "test!";
  }


The code messes up when I try to make node n2 on the second go-round. Heap returns a node with two children, each child has NULL children, but when it's assigned to n2, n2's children (who should be identical to what heap returned) are different. Specifically the right child's right_ pointer points to itself.

My Constructors:
1
2
3
4
5
6
7
8
9
10
11
12
Node<T,V>()                                  : left_(NULL),         right_(NULL),         value_(0) {}
  Node<T,V>(T id, V value)                     : left_(NULL),         right_(NULL),         value_(value),        id_(id) {}
  Node<T,V> (const Node<T,V> &node)            : left_(node.left()),  right_(node.right()), value_(node.Value()), id_(node.Id()) {}
  Node<T,V> (Node<T,V> &a, Node<T,V> &b)       : left_(&a),           right_(&b),           value_(a.Value() + b.Value()) {}
  Node<T,V> operator =(const Node<T,V>& node)
  {
    this->left_ = node.left();
    this->right_ = node.right();
    this->value_ = node.Value();
    this->id_ = node.Id();
    return *this;
  }



Any thoughts? Any more code I can provide?
Last edited on
Went with a different way of declaring these:
1
2
3
4
5
6
7
  while (heap.size() > 1)
  {
    Node<char, long> *n1 = new Node<char,long>(pop_element(heap));
    Node<char, long> *n2 = new Node<char,long>(pop_element(heap));
    Node<char, long> n(n1, n2);
    insert(heap, n);
  }


And:
Node<T,V> (Node<T,V> *a, Node<T,V> *b) : left_(a), right_(b), value_(a->Value() + b->Value()) {}

Works now.
Last edited on
Topic archived. No new replies allowed.