I would like to ask if the implementation is ok, and what I can improve. Although I'm not sure if the Singleton is working properly.
class MyLinkedList<T>
{
class Node<G>
{
public Node<G> next;
public G Data;
public Node(G data)
{
Data = data;
next = null;
}
}
private Node<T> head;
private Node<T> tail;
public T First => head.Data;
public T Last => tail.Data;
public MyLinkedList()
{
head = tail = null;
}
public void Add(T data)
{
Node<T> node = new Node<T>(data);
if (head == null)
{
head = node;
tail = node;
}
else
{
tail.next = node;
tail = node;
}
}
public void RemoveByIndex(int index)
{
int count = 0;
Node<T> current = head;
Node<T> previous = current;
try
{
while (count <= index)
{
if (count == index)
{
previous.next = current.next;
current = null;
}
else
{
previous = current;
current = current.next;
}
count++;
}
}
catch (NullReferenceException)
{
Console.WriteLine("Invalid index to remove");
}
}
public override string ToString()
{
StringBuilder list = new StringBuilder();
Node<T> index = head;
while (index.next != null)
{
list.Append($"{index.Data} -> ");
index = index.next;
}
list.Append(index.Data);
return list.ToString();
}
}
public class Singleton<T> where T : class, new()
{
private Singleton() { }
private static readonly Lazy<T> instance = new Lazy<T>(() => new T());
public static T Instance { get { return instance.Value; } }
}