Added Delete Method and updated Indexing Methods

This commit is contained in:
Luke Else 2022-03-04 10:49:08 +00:00
parent 02f49782ee
commit 8165bb849b
2 changed files with 34 additions and 2 deletions

View File

@ -91,6 +91,36 @@ namespace C_.Datastructures
}; };
} }
public void Insert(int index, T value)
{
if (index > Count) throw new System.Exception("Error! Index outside of Bounds");
//Fetch point in list at which item will be added
Node<T>? node = Traverse(index - 1);
node!.Next = new Node<T> {
Value = value,
Next = node.Next
};
Count++;
}
public void Delete(int index)
{
if (index == 0 && Head != null)
{
Head = (Node<T>?)Head!.Next;
return;
}
Node<T>? node = Traverse(index - 1);
if (node == null || node.Next == null) throw new System.Exception("Error! Index outside of Bounds");
node.Next = node.Next.Next;
Count--;
}
private Node<T>? Traverse(){ private Node<T>? Traverse(){
//Start at Head of list //Start at Head of list
Node<T>? node = Head; Node<T>? node = Head;
@ -123,12 +153,12 @@ namespace C_.Datastructures
{ {
//Start at given point in list //Start at given point in list
Node<T>? node = Head; Node<T>? node = Head;
if (node != null) if (node != null || n == 0)
{ {
//Continue to end of list //Continue to end of list
for (int i = 0; i < n; i++) for (int i = 0; i < n; i++)
{ {
if (node.Next == null) return null; if (node!.Next == null) return null;
node = (Node<T>)node.Next; node = (Node<T>)node.Next;
} }
} }

View File

@ -20,4 +20,6 @@ list2.Append(3);
LinkedList<int> list3 = LinkedList<int>.Create(list, list2); LinkedList<int> list3 = LinkedList<int>.Create(list, list2);
int x = list3[5] = 5; int x = list3[5] = 5;
list3.Insert(4, 1);
list3.Delete(0);
Console.ReadLine(); Console.ReadLine();