DataStructuresCSharp/C#/Datastructures/LinkedList.cs

138 lines
3.7 KiB
C#

using C_.Datastructures.Nodes;
namespace C_.Datastructures
{
public class LinkedList<T>
{
public Node<T>? Head { get; set; } = default(Node<T>);
private int Count { get; set; } = 0;
public static LinkedList<T> Create(){
//Create a new empty list
return new LinkedList<T>();
}
public static LinkedList<T> Create(T value){
//Create a new Class with a single item
return new LinkedList<T>(){
Head = Node<T>.Create(value, null),
Count = 1
};
}
public static LinkedList<T> Create(LinkedList<T> list1, LinkedList<T> list2){
//Append a previous list to a new List
LinkedList<T> list;
list = list1;
if (list == null || list.Count == 0)
{
//If list 2 is the only list present
return list2;
}
//Find end of list and append fist item of next list
if (list2 == null || list.Count == 0) return list;
Node<T>? end = list.Traverse();
end!.Next = list2!.Head;
list.Count += list2!.Count;
return list;
}
public T? this[int i]
{
get {
//Check Range
if (i >= Count) throw new System.Exception("Error! Index out of Bounds");
//Return Value
Node<T>? node = Traverse(i);
if (node != null) return node.Value;
return default(T);
}
set
{
//Check Range
if (i >= Count) throw new System.Exception("Error! Index out of Bounds");
//Change Value
Node<T>? node = Traverse(i);
node!.Value = value;
}
}
public void Append(T value){
Node<T> newItem = Node<T>.Create(value, default(Node<T>));
Count++;
//Set head to new item if list is empty
if (Head == null)
{
Head = newItem;
return;
}
//Find last item in list
Node<T>? end = Head;
if (end != null)
{
end = Traverse();
}
//Append item to end
end!.Next = new Node<T>{
Value = value,
Next = default(Node<T>)
};
}
private Node<T>? Traverse(){
//Start at Head of list
Node<T>? node = Head;
if (node != null)
{
//continue to end of list
while (node!.Next != default(Node<T>))
{
node = (Node<T>)node.Next;
}
}
return node;
}
private Node<T>? Traverse(Node<T> start){
//Start at given point in list
Node<T>? node = start;
if (node != null)
{
//Continue to end of list
while (node!.Next != default(Node<T>))
{
node = (Node<T>)node.Next;
}
}
return node;
}
private Node<T>? Traverse(int n)
{
//Start at given point in list
Node<T>? node = Head;
if (node != null)
{
//Continue to end of list
for (int i = 0; i < n; i++)
{
if (node.Next == null) return null;
node = (Node<T>)node.Next;
}
}
return node;
}
}
}