Write a program to create a singly linked list of n nodes and count the number of nodes
Solution
using System;
namespace LinkedListOpearation
{
class Program
{
public static void Main()
{
var linkedList = new LinkedList();
linkedList.Add(6);
linkedList.Add(1);
linkedList.Add(5);
linkedList.Add(2);
linkedList.Add(3);
linkedList.Add(9);
Console.WriteLine("Sorted Linked List is:");
linkedList.Print(linkedList.Head);
Console.WriteLine($"Total count of nodes: {linkedList.Count(linkedList.Head)}");
Console.ReadLine();
}
}
public class LinkedList
{
public Node Head;
public void Add(int data)
{
var node = new Node(data) {Next = Head};
Head = node;
}
public int Count(Node head)
{
var count = 0;
var current = head;
while (current != null)
{
count++;
current = current.Next;
}
return count;
}
public void Print(Node head)
{
while (head != null)
{
Console.WriteLine(head.Data);
head = head.Next;
}
}
}
public class Node
{
public int Data;
public Node Next;
public Node(int data)
{
Data = data;
}
}
}