开发者

linked list and Red/Black tree in c# - reference problem?

开发者 https://www.devze.com 2022-12-21 05:58 出处:网络
I\'m pretty new to c#, and i\'m trying to understand something pretty basic. I want to implement a RBTree and a linked list , so i create :

I'm pretty new to c#, and i'm trying to understand something pretty basic.

I want to implement a RBTree and a linked list , so i create :

public class RBTreeNode
{
        // PROPERTIES
        public RBTreeNode left;
        pu开发者_C百科blic RBTreeNode right;
        public RBTreeNode parent;
        public String Color;
        public Int Key;
} 

List<RBTreeNode> deleteList = new List<RBTreeNode>();

During the running of my program i iterate through the tree, taking some nodes (depending on the value) , and adding them to deleteList.

the thing that i can't set my mind to, is if for example i have RBTreeNode X , and i do X.left = null. the thing i want to happen is nulling X's left child (without affecting X.left RBTreeNode , but what i think will happen here is that indeed X.left will become null, but the X.left RBTreeNode object will become also null. which is not what i want. (if it's copied to deleteList , it will become null, which is wrong)

I want to be able to do the same thing i do with c++ using pointers. In c++ i might do it like :

public class RBTreeNode
{
        // PROPERTIES
        public RBTreeNode* left;
        public RBTreeNode* right;
        public RBTreeNode* parent;
        public std::string Color;
        public int Key;
} 

For example :

RBTreeNode* tenp = X->left;
X->left = null; //(i think in c# it will turn temp here to null to - of course without   pointers)
temp->right = &X;

Any tips/explanations ?


No, you're fine. X.left is just a variable. Setting it to null just sets the value of that variable to null, it does nothing to the object that it used to refer to.

There's really no such concept as setting an object to null in C#.

I have an article about value and reference types in C# that you may find useful.


the properties are references, so the underlying contents wont be changed. you can swap using a temp variable, similar to the c++ version (except no pointers of course).

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号