Search code examples
c#.netlistdata-structureslinked-list

C# Multiway Linked List


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?


Solution

  • 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);