Mike Plott
Mike Plott

Reputation: 327

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?

Upvotes: 5

Views: 227

Answers (2)

Reed Copsey
Reed Copsey

Reputation: 564921

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.

Upvotes: 5

Sean U
Sean U

Reputation: 6850

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

class Reference<T>
{
    public T Value {get; set;}
}

Upvotes: 5

Related Questions