Reputation:
I am trying to add new movie name in the existing linked list but got error.
cannot convert from 'string' to 'System.Collections.Generic.LinkedListNode<string>'
Here is code I am working on it:
LinkedList<string> movies = new LinkedList<string>();
movies.AddLast("Fire & Dew");
movies.AddLast("Hang Break");
movies.AddLast("Naughty Monkey");
movies.AddLast("Sabotage");
//Add movie name Good & Bad After Hang Break
movies.AddAfter("Hang Break", "Good & Bad");
foreach (string movie in movies)
{
Console.WriteLine(movie);
}
Any solution and code tip?
Upvotes: 3
Views: 2420
Reputation: 476659
Well the type signature of AddAfter
is:
public LinkedListNode<T> AddAfter(LinkedListNode<T> node, T value)
So the first parameter node
should be a LinkedListNode<T>
. You can obtain that node since it is returned from the AddLast
method:
movies.AddLast("Fire & Dew");
var hang_break = movies.AddLast("Hang Break");
movies.AddLast("Naughty Monkey");
movies.AddLast("Sabotage");
//Add movie name Good & Bad After Hang Break
movies.AddAfter(hang_break, "Good & Bad");
After we've evaluated this code in the csharp
interactive shell, we obtain:
csharp> movies
{ "Fire & Dew", "Hang Break", "Good & Bad", "Naughty Monkey", "Sabotage" }
The reason why this is necessary is because such linked list allows insertion next to the given node in O(1) since it modifies the references of the next and previous node. This can be done since it only needs to alter the given node and the node next to the given node. If you however first need to search the node, then the algorithm is O(n) and so the performance advantage of a linked list will be lost.
Upvotes: 7