C# program to traverse circular singly LinkedList
Here's an example of a C# program that traverses a circular singly built-in LinkedList and prints its elements:
using System;
using System.Collections.Generic;
class Program
{
static void TraverseCircularLinkedList(LinkedList list)
{
if (list.First == null)
{
Console.WriteLine("The list is empty.");
return;
}
var currentNode = list.First;
do
{
Console.WriteLine(currentNode.Value);
currentNode = currentNode.Next;
}
while (currentNode != list.First);
}
static void Main()
{
// Creating a circular singly LinkedList
var linkedList = new LinkedList();
linkedList.AddLast(1);
linkedList.AddLast(2);
linkedList.AddLast(3);
linkedList.AddLast(4);
linkedList.AddLast(5);
linkedList.AddLast(6);
// Making the LinkedList circular by connecting the last node to the first node
linkedList.Last.Next = linkedList.First;
// Traversing the circular LinkedList and printing its elements
TraverseCircularLinkedList(linkedList);
}
}
In this program, we define a TraverseCircularLinkedList function that takes a circular singly LinkedList as input and traverses it by starting from the first node (First) and moving to the next node (Next) until reaching the first node again (list.First). We use a do-while loop to ensure that the traversal continues even if the list is initially empty. Each element is printed using Console.WriteLine. The Main function demonstrates the usage of this function by creating a circular LinkedList, connecting the last node to the first node to make it circular, and then calling TraverseCircularLinkedList to print its elements. The output of this example will be:
1
2
3
4
5
6
Please note that in a circular LinkedList, the last node's Next property should point to the first node to make it circular.