Reputation: 4897
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?
Upvotes: 1
Views: 2605
Reputation: 18443
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);
Upvotes: 3
Reputation: 6723
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).
Upvotes: 2