diff --git a/C#/Datastructures/DoublyLinkedList.cs b/C#/Datastructures/DoublyLinkedList.cs index b93eae9..fa9caf6 100644 --- a/C#/Datastructures/DoublyLinkedList.cs +++ b/C#/Datastructures/DoublyLinkedList.cs @@ -78,36 +78,39 @@ namespace C_.Datastructures { Count++; - if (Tail != null && Count > 0) - { - Tail.Next = new DoublyLinkedListNode { Value = value, Next = default, Prev = Tail }; - Tail = Tail.Next; + //Set head to new item if list is empty + if (Head == null) + {//Append item to front of list (End as well) + Head = DoublyLinkedListNode.Create(value, default, default); + Tail = Head; return; } - Head = new DoublyLinkedListNode { Value = value, Next = default, Prev = default }; - Tail = Head; - + //Append item to the end of the list + Tail!.Next = DoublyLinkedListNode.Create(value, default, Tail); + Tail = Tail.Next; } 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 = DoublyLinkedListNode.Create(value, Head, default); + Tail = Head; + return; + } + //Fetch point in list and add new item DoublyLinkedListNode? node = Traverse(index - 1); - node!.Next = new DoublyLinkedListNode{ - Value = value, - Next = node.Next, - Prev = node - }; + node!.Next = DoublyLinkedListNode.Create(value, node.Next, node); //Create backlink in the list if(node.Next.Next != default) node.Next.Next.Prev = node.Next; - - Count++; - } public bool Delete(int index){