Skip to content
Related Articles

Related Articles

C# | Find the first node in LinkedList<T> containing the specified value
  • Last Updated : 01 Feb, 2019

LinkedList<T>.Find(T) method is used to find the first node that contains the specified value.

Syntax:

public System.Collections.Generic.LinkedListNode<T> Find (T value);

Here, value is the value to locate in the LinkedList.

Return Value: This method returns the first LinkedListNode<T> that contains the specified value, if found, otherwise, null.

Below given are some examples to understand the implementation in a better way:



Example 1:




// C# code to find the first node
// that contains the specified value
using System;
using System.Collections;
using System.Collections.Generic;
  
class GFG {
  
    // Driver code
    public static void Main()
    {
        // Creating a LinkedList of Strings
        LinkedList<String> myList = new LinkedList<String>();
  
        // Adding nodes in LinkedList
        myList.AddLast("A");
        myList.AddLast("B");
        myList.AddLast("C");
        myList.AddLast("D");
        myList.AddLast("E");
  
        // Finding the first node that
        // contains the specified value
        LinkedListNode<String> temp = myList.Find("B");
  
        Console.WriteLine(temp.Value);
    }
}

Output:

B

Example 2:




// C# code to find the first node
// that contains the specified value
using System;
using System.Collections;
using System.Collections.Generic;
  
class GFG {
  
    // Driver code
    public static void Main()
    {
        // Creating a LinkedList of Integers
        LinkedList<int> myList = new LinkedList<int>();
  
        // Adding nodes in LinkedList
        myList.AddLast(5);
        myList.AddLast(7);
        myList.AddLast(9);
        myList.AddLast(11);
        myList.AddLast(12);
  
        // Finding the first node that
        // contains the specified value
        LinkedListNode<int> temp = myList.Find(15);
  
        Console.WriteLine(temp.Value);
    }
}

Runtime Error:

Unhandled Exception:
System.NullReferenceException: Object reference not set to an instance of an object

Note:

  • The LinkedList is searched forward starting at First and ending at Last.
  • This method performs a linear search. Therefore, this method is an O(n) operation, where n is Count.

Reference:

My Personal Notes arrow_drop_up
Recommended Articles
Page :