Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement this struct as a class without pointers in c#?

Node of the list where every element points to next element and the head of the list would look like this :

typedef struct Node {
   int value;
   Node* next;
   Node** head;
} Node;

head can change, therefore we were using Node ** head. I know classes are passed as reference, so I can make first 2 attributes like this:

class Node {
  int value;
  Node next;
  ???? 
}

How to make the head attribute?

like image 201
Mike Plott Avatar asked Dec 20 '11 01:12

Mike Plott


2 Answers

Make a wrapper class to take the place of a double pointer:

class Reference<T>
{
    public T Value {get; set;}
}
like image 123
Sean U Avatar answered Nov 14 '22 22:11

Sean U


Typically, this is handled by passing a reference to the containing object. If this is for a linked list, for example, you might do:

class Node
{
    int Value { get; set; }
    Node Next { get; set; }
    LinkedList list;

    Node Head { get { return list.Head; } }

    public Node(LinkedList parent)
    {
       this.list = parent;
    }
}

This way, when the "head" element of the actual list containing the node changes, the property in the class will automatically reflect the new value.

like image 44
Reed Copsey Avatar answered Nov 14 '22 23:11

Reed Copsey