Open In App
Related Articles

C# | Find the last node in LinkedList<T> containing the specified value

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report
LinkedList<T>.FindLast(T) method is used to find the last node that contains the specified value. Syntax:
public System.Collections.Generic.LinkedListNode<T> FindLast (T value);
Here, value is the value to locate in the LinkedList. Return Value: This method returns the last 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 last 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 last node that
        // contains the specified value
        LinkedListNode<String> temp = myList.Find("D");
  
        Console.WriteLine(temp.Value);
    }
}

                    
Output:
D
Example 2:
// C# code to find the last 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 last node that
        // contains the specified value
        LinkedListNode<int> temp = myList.Find(2);
  
        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 backward starting at Last and ending at First.
  • This method performs a linear search. Therefore, this method is an O(n) operation, where n is Count.
Reference:

Last Updated : 01 Feb, 2019
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads