Updated Append and Delete methods in Doubly Linked List
This commit is contained in:
parent
1998e77f18
commit
f2c3e74d15
@ -78,36 +78,39 @@ namespace C_.Datastructures
|
||||
{
|
||||
Count++;
|
||||
|
||||
if (Tail != null && Count > 0)
|
||||
{
|
||||
Tail.Next = new DoublyLinkedListNode<T> { 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<T>.Create(value, default, default);
|
||||
Tail = Head;
|
||||
return;
|
||||
}
|
||||
|
||||
Head = new DoublyLinkedListNode<T> { Value = value, Next = default, Prev = default };
|
||||
Tail = Head;
|
||||
|
||||
//Append item to the end of the list
|
||||
Tail!.Next = DoublyLinkedListNode<T>.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<T>.Create(value, Head, default);
|
||||
Tail = Head;
|
||||
return;
|
||||
}
|
||||
|
||||
//Fetch point in list and add new item
|
||||
DoublyLinkedListNode<T>? node = Traverse(index - 1);
|
||||
node!.Next = new DoublyLinkedListNode<T>{
|
||||
Value = value,
|
||||
Next = node.Next,
|
||||
Prev = node
|
||||
};
|
||||
node!.Next = DoublyLinkedListNode<T>.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){
|
||||
|
Loading…
Reference in New Issue
Block a user