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

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:

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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);
    }
}

chevron_right


Output:

D

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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);
    }
}

chevron_right


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:



My Personal Notes arrow_drop_up

In love with a semicolon because sometimes i miss it so badly)

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.