Updated Delete and Appends methods on linked list
This commit is contained in:
@ -61,6 +61,7 @@ namespace C_.Datastructures
|
||||
}
|
||||
|
||||
public void Append(T value){
|
||||
//Create new node
|
||||
LinkedListNode<T> newItem = LinkedListNode<T>.Create(value, default);
|
||||
Count++;
|
||||
|
||||
@ -77,44 +78,48 @@ namespace C_.Datastructures
|
||||
{
|
||||
end = Traverse();
|
||||
}
|
||||
|
||||
|
||||
//Append item to end
|
||||
end!.Next = new LinkedListNode<T>{
|
||||
Value = value,
|
||||
Next = default
|
||||
};
|
||||
end!.Next = newItem;
|
||||
|
||||
}
|
||||
|
||||
public void Insert(int index, T value)
|
||||
{
|
||||
if (index > Count) throw new System.Exception("Error! Index outside of Bounds");
|
||||
|
||||
Count++;
|
||||
|
||||
//Set head to new item if list is empty
|
||||
if (index == 0 || Head == null)
|
||||
{
|
||||
Head = LinkedListNode<T>.Create(value, Head);
|
||||
return;
|
||||
}
|
||||
|
||||
//Fetch point in list at which item will be added
|
||||
LinkedListNode<T>? node = Traverse(index - 1);
|
||||
|
||||
node!.Next = new LinkedListNode<T> {
|
||||
Value = value,
|
||||
Next = node.Next
|
||||
};
|
||||
Count++;
|
||||
node!.Next = LinkedListNode<T>.Create(value, node!.Next);
|
||||
}
|
||||
|
||||
public void Delete(int index)
|
||||
{
|
||||
if (index > Count) throw new System.Exception("Error! Index outside of Bounds");
|
||||
|
||||
Count--;
|
||||
|
||||
//Check if we are trying to reference the first item
|
||||
if (index == 0 && Head != null)
|
||||
{
|
||||
Head = (LinkedListNode<T>?)Head!.Next;
|
||||
Head = Head!.Next;
|
||||
return;
|
||||
}
|
||||
|
||||
//Find node we are trying to delete and then remove / relink
|
||||
//Find node before the one we are trying to delete and then remove / relink
|
||||
LinkedListNode<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--;
|
||||
node!.Next = node.Next!.Next;
|
||||
}
|
||||
|
||||
private LinkedListNode<T>? Traverse(){
|
||||
|
Reference in New Issue
Block a user