5

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?

2 Answers 2

5

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

class Reference<T>
{
    public T Value {get; set;}
}
Sign up to request clarification or add additional context in comments.

4 Comments

And how does this solve the problem here? Using Reference<Node> still won't cause a change in the parent node to be reflected locally...
It will if every Node's head is the same instance of Reference.
The LinkedList in @ReedCopsey 's answer should also use that same Reference instance to find its head node. Then it works, but I'm not sure this is the "right" way of doing it.
Agreed. The right way to do it would be to just use List<T> or LinkedList<T>. But if you're porting code, sometimes it's convenient to keep things as close as possible to how the original worked for the first iteration.
5

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.