Reputation: 138
I've searched so long and hard for this and now I'm at road's end. I've had this issue with more than this project, but I ended up scrapping the others. I have a code (C#) which is basically me trying to do Huffman tree. At one point I do this ("nodeList" is List(Node)):
Node node = new Node(nodeList[0], nodeList[1]);
nodeList.Add(node); // Adds a new node which includes two subnodes.
// Remove nodes from list (as they are now included in another node)
nodeList.RemoveAt(0);
nodeList.RemoveAt(1);
And the constructors in use here is:
// Constructor that takes nodes
public Node(Node left, Node right)
{
leftNode = new Node(left);
rightNode = new Node(right);
}
// Constructor that only takes 1 single node
public Node(Node copy)
{
rightNode = copy.rightNode;
leftNode = copy.leftNode;
unencodedBits = copy.unencodedBits;
encodingValue = copy.encodingValue;
positions = copy.positions;
}
I did the second constructor as a hope that it would fix my problem (thinking that removing the node from the list maybe nulled it out.) (all of the values in my Node-class is on the right side of the second constructor.)
The problem: After doing the second "RemoveAt" the Node will no longer contain the two nodes. And I can not understand why. What do I have to do to prevent this from happening and why does it happen (so I can understand similar cases in the future)?
I probably forgot to include some vital information; If I did, please tell me. And thanks for any assistance.
Upvotes: 0
Views: 339
Reputation: 2178
Is your nodeList object in array or a List? If it is a list, then nodeList.RemoveAt(0) causes the node currently located and index 1 to now be located at index 0. so you would need to call
nodeList.RemoveAt(0);
nodeList.RemoveAt(0);
instead of
nodeList.RemoveAt(0);
nodeList.RemoveAt(1);
see here: http://msdn.microsoft.com/en-us/library/5cw9x18z(v=vs.110).aspx
Upvotes: 1