C# program to traverse singly LinkedList
Here's an example of a C# program that traverses a singly built-in LinkedList and prints its elements:
using System;
using System.Collections.Generic;
class Program
{
static void TraverseLinkedList(LinkedList list)
{
var currentNode = list.First;
while (currentNode != null)
{
Console.WriteLine(currentNode.Value);
currentNode = currentNode.Next;
}
}
static void Main()
{
// Creating a singly LinkedList
var linkedList = new LinkedList();
linkedList.AddLast(1);
linkedList.AddLast(2);
linkedList.AddLast(3);
linkedList.AddLast(4);
linkedList.AddLast(5);
// Traversing the LinkedList and printing its elements
TraverseLinkedList(linkedList);
}
}
In this program, we define a TraverseLinkedList function that takes a singly LinkedList as input and traverses it by starting from the first node (First) and moving to the next node (Next) until reaching the end of the list (null). During traversal, each element is printed using Console.WriteLine. The Main function demonstrates the usage of this function by creating a LinkedList, adding elements to it, and then calling TraverseLinkedList to print its elements. The output of this example will be:
1
2
3
4
5
This program assumes the LinkedList is singly linked, where each node only contains a reference to the next node and not the previous node.