I just need some help with linkedlists in C#, linked-list in C++ is kinda easy with pointers but im facing some problems in C#
I read the examples provided on http://msdn.microsoft.com but I couldn’t figure out how to link two different linked lists
the efficitent way seems to be having LinkedListNode into a linked list , so lets say I have two linked lists
LinkedList L1 = new LinkedList();
LinkedList L2 = new LinkedList();
and then lets say I have the following nodes
LinkedListNode<String> Ln1 = new LinkedListNode<String>("Orange");
LinkedListNode<String> Ln2 = new LinkedListNode<String>("Banana");
LinkedListNode<String> Ln3 = new LinkedListNode<String>("Apple");
LinkedListNode<String> Ln4 = new LinkedListNode<String>("Strawberry");
I simply added them to the lists I have :
L1.AddLast(Ln1);
L1.AddLast(Ln2);
L2.AddLast(Ln3);
L2.AddLast(Ln4);
Ok now lets say I want to link the last element of L1 to the first one in L2 , is that possible ?
I tried this first :
L1.Last.Next = L2.First;
I totally failed with an error : Property or indexer ‘System.Collections.Generic.LinkedListNode&lt;string>.Next’ cannot be assigned to — it is read only
alright I tried this then :
Ln2.Next = Ln3;
I failed again
my last attempt was
LinkedListNode<String> node1=L1.Last;
LinkedListNode<String> node2 = L2.First;
node1.Next = node2;
with an error :Property or indexer ‘System.Collections.Generic.LinkedListNode&lt;string>.Next’ cannot be assigned to — it is read only
so any help please ? how to link them ?
an addition questions :
is there away to reach an element in a linked list by its index for example ?
I came out with this simple algorithm and it works :
int i = 0;
foreach (var item in L2)
{
Console.WriteLine(item);
i++;
}
is there an automatic way ?
thank you for your help
LinkedListNode has property List. This property points to list, which node belongs to. This property is set when you adding node to some list. So, at one time node could belong only to one list. That means you should remove node from one list, before adding it to another:
If you want to add all nodes from L2, you can use:
Keep in mind, it will remove all nodes from L2.
Another option – create new nodes with same values:
UPDATE: If you want to reach an element in a linked list by its index, you can just skip first N items and take next one:
As with any collection, you should verify, that list has at least N-1 nodes.