1

Is there a way to make a LinkedList in C# point to multiple children, rather than just one? i.e. Is there a way to turn it into a Multi-Way Linked List?

2 Answers 2

3

You need to create list of lists:

LinkedList<LinkedList<int>> l = new LinkedList<LinkedList<int>>();

But that depends on your exact problem.

If you want to have more control over what you want to store, you should create your own data structure and store that in the list:

public class MyNodeData
{
    public MyNodeData()
    {
        Children = new LinkedList<MyNodeData>();
    }

    public MyNodeData(int i, string s)
        : this()
    {
        MyInt = i;
        MyString = s;
    }

    public int MyInt { get; set; }
    public string MyString { get; set; }

    public LinkedList<MyNodeData> Children { get; private set; }
}

This is just a sample and you may define any properties of any type by any desired name.
Then add the data:

    LinkedList<MyNodeData> l = new LinkedList<MyNodeData>();

    var d = new MyNodeData();
    d.MyInt = 10;
    d.MyString = "Node message";
    d.Children.AddLast(new MyNodeData(11, "Child 1 message"));
    d.Children.AddLast(new MyNodeData(12, "Child 2 message"));
    l.AddLast(d);

    Console.WriteLine(l.First.Value.MyString);
    Console.WriteLine(l.First.Value.Children.Last.Value.MyInt);
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for the reply. If I use this approach, how exactly would I store the 'parent' object, if I can only store a list of its children?
In other words, if I have a Node '1', and I want to store this node's ID, how can I do that if all I can store is a list with its children?
Well, this is a new thing! So you want to store some data in addition to the children. OK. I modify the answer to address that one!
Thanks for the help, I think I'll try something similar! :)
2

What you are describing is either a graph or a tree data structure. I think the clearest way to implement this would be to create your own data structure such as a node. You may want to read up more on graphs here: http://en.wikipedia.org/wiki/Graph_(abstract_data_type).

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.