Updated bounds search on Doubly Linked List and completed traverse method

This commit is contained in:
Luke Else 2022-03-10 21:26:16 +00:00
parent bd5c546794
commit 79debf3d62
2 changed files with 44 additions and 20 deletions

View File

@ -33,7 +33,7 @@ namespace C_.Datastructures
get get
{ {
//Check Range //Check Range
if (i >= Count) throw new System.Exception("Error! Index out of Bounds"); if (i >= Count || i < 0) throw new System.Exception("Error! Index out of Bounds");
//Return Value //Return Value
DoublyLinkedListNode<T>? node = Traverse(i); DoublyLinkedListNode<T>? node = Traverse(i);
@ -43,13 +43,28 @@ namespace C_.Datastructures
set set
{ {
//Check Range //Check Range
if (i >= Count) throw new System.Exception("Error! Index out of Bounds"); if (i >= Count || i < 0) throw new System.Exception("Error! Index out of Bounds");
//Change Value //Change Value
DoublyLinkedListNode<T>? node = Traverse(i); DoublyLinkedListNode<T>? node = Traverse(i);
node!.Value = value; node!.Value = value;
} }
} }
public void Add(T value)
{
Count++;
if (Tail != null && Count > 0)
{
Tail.Next = new DoublyLinkedListNode<T> { Value = value, Next = null, Prev = Tail };
Tail = Tail.Next;
return;
}
Head = new DoublyLinkedListNode<T> { Value = value, Next = null, Prev = null };
Tail = Head;
}
private DoublyLinkedListNode<T>? Traverse() private DoublyLinkedListNode<T>? Traverse()
@ -66,17 +81,30 @@ namespace C_.Datastructures
if (i > (Count/2)) if (i > (Count/2))
{ {
//reverse direction of search
direction = -1; direction = -1;
node = Tail; node = Tail;
i = Count - i; //i becomes the amount of hops left to reach the item
i = Count - i - 1;
} }
if (node != null) if (node != null)
{ {
//continue to end of list
//continue to given point in the list ('i' hops)
for (int x = 0; x < i; x++) for (int x = 0; x < i; x++)
{ {
//Incomplete Traverse Functions if (direction == 1)
{//Going forwards
node = node!.Next;
}
else
{
node = node!.Prev;
}
} }
} }
return node; return node;

View File

@ -5,22 +5,18 @@ using C_.Datastructures.Nodes;
// See https://aka.ms/new-console-template for more information // See https://aka.ms/new-console-template for more information
Console.WriteLine("Hello, World!"); Console.WriteLine("Hello, World!");
LinkedList<int> list = new(); DoublyLinkedList<int> list = new DoublyLinkedList<int>();
list.Append(1); list.Add(1);
list.Append(2); list.Add(2);
list.Append(3); list.Add(3);
list.Add(4);
list.Add(5);
list.Add(6);
list.Add(7);
list.Add(8);
LinkedList<int> list2 = new(); var x = list[-6];
list2.Append(1); Console.WriteLine(x);
list2.Append(2);
list2.Append(3);
LinkedList<int> list3 = LinkedList<int>.Create(list, list2);
list3.Insert(4, 1);
list3.Delete(0);
list3.Head = LinkedListNode<int>.Create(5, null);
Console.ReadLine();