简体   繁体   中英

Update value of a Node in a Linked List in C#

I 've tried Linked list operations. And I'm able to add/ remove Node s in the list. But I'm unable to update a value of a Node in the List.

I have removed the current Node's value. So when I remove the value, will the node also removed?? or if the Node is still available Can I update the value of that.

Here is my Code

static void Main(string[] args)
{
    string[] words = { "the", "fox", "jumped", "over", "the", "dog" };
    LinkedList<string> sentence = new LinkedList<string>(words);

   // sentence.RemoveFirst();
    sentence.AddFirst("today");
    LinkedListNode<string> current = sentence.Find("jumped");
    sentence.AddAfter(current, "XXX");

    LinkedListNode<string> mark1 = current.Previous;
    sentence.AddAfter(mark1, "ZZZ");
    sentence.Remove(current.Value);
    // I have removed the current's value

    foreach (string s in sentence)
    {
        Console.WriteLine(s);
    }

    Console.ReadLine();
}

You don't need to replace the node, just change its value

sentance.Find("jumped").Value = "over"

...

static void Main(string[] args)
{
    string[] words = { "the", "fox", "jumped", "over", "the", "dog" };
    LinkedList<string> sentence = new LinkedList<string>(words);

    sentance.Find("jumped").Value = "over"

    foreach (string s in sentence)
    {
        Console.WriteLine(s);
    }

    Console.ReadLine();
}

You are using the LinkedList<T>.Remove Method which removes the whole node, not just clear the value. see MSDN

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM