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:
using System;
using System.Collections;
using System.Collections.Generic;
class GFG {
public static void Main()
{
LinkedList<String> myList = new LinkedList<String>();
myList.AddLast( "A" );
myList.AddLast( "B" );
myList.AddLast( "C" );
myList.AddLast( "D" );
myList.AddLast( "E" );
LinkedListNode<String> temp = myList.Find( "D" );
Console.WriteLine(temp.Value);
}
}
|
Output:
D
Example 2:
using System;
using System.Collections;
using System.Collections.Generic;
class GFG {
public static void Main()
{
LinkedList< int > myList = new LinkedList< int >();
myList.AddLast(5);
myList.AddLast(7);
myList.AddLast(9);
myList.AddLast(11);
myList.AddLast(12);
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
Share your thoughts in the comments
Please Login to comment...