C# program to find node in Linkedlist
Here's an example of a C# program that demonstrates how to find a node in a built-in LinkedList in C#. It includes a method to find a specific node based on a given value, along with an example usage that creates a LinkedList, adds elements to it, searches for a node with a specific value, and displays the search result.
using System;
using System.Collections.Generic;
class Program
{
static void Main(string[] args)
{
// Create a LinkedList and add elements
LinkedList linkedList = new LinkedList();
linkedList.AddLast(1);
linkedList.AddLast(2);
linkedList.AddLast(3);
linkedList.AddLast(4);
linkedList.AddLast(5);
// Search for a node with value 3
LinkedListNode foundNode = FindNode(linkedList, 3);
// Display the search result
if (foundNode != null)
{
Console.WriteLine("Node found: " + foundNode.Value);
}
else
{
Console.WriteLine("Node not found.");
}
}
static LinkedListNode FindNode(LinkedList list, T value)
{
LinkedListNode currentNode = list.First;
while (currentNode != null)
{
if (currentNode.Value.Equals(value))
{
return currentNode;
}
currentNode = currentNode.Next;
}
return null;
}
}
Output:
Node found: 3
In this example, we use the 'LinkedList' class in C# to represent the linked list. We create a 'LinkedList' and add elements to it using the 'AddLast' method.
The 'FindNode' method takes a 'LinkedList' and a value as input and searches for a node with the specified value. It uses a currentNode variable to iterate over the nodes in the list. Starting from the first node, it compares the value of each node with the given value using the 'Equals' method. If a match is found, it returns the node. If no matching node is found, it returns null.
In the 'Main' method, we create a 'LinkedList', add elements to it, call the 'FindNode' method to search for a node with the value 3, and then display the search result. If the node is found, we print its value. Otherwise, we print a message indicating that the node was not found.