From 79debf3d620c2fcd89ad33819d709209c88c16af Mon Sep 17 00:00:00 2001 From: Luke Else Date: Thu, 10 Mar 2022 21:26:16 +0000 Subject: [PATCH] Updated bounds search on Doubly Linked List and completed traverse method --- C#/Datastructures/DoublyLinkedList.cs | 38 +++++++++++++++++++++++---- C#/Program.cs | 26 ++++++++---------- 2 files changed, 44 insertions(+), 20 deletions(-) diff --git a/C#/Datastructures/DoublyLinkedList.cs b/C#/Datastructures/DoublyLinkedList.cs index 63d23a0..ffd668c 100644 --- a/C#/Datastructures/DoublyLinkedList.cs +++ b/C#/Datastructures/DoublyLinkedList.cs @@ -33,7 +33,7 @@ namespace C_.Datastructures get { //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 DoublyLinkedListNode? node = Traverse(i); @@ -43,13 +43,28 @@ namespace C_.Datastructures set { //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 DoublyLinkedListNode? node = Traverse(i); node!.Value = value; } } + public void Add(T value) + { + Count++; + + if (Tail != null && Count > 0) + { + Tail.Next = new DoublyLinkedListNode { Value = value, Next = null, Prev = Tail }; + Tail = Tail.Next; + return; + } + + Head = new DoublyLinkedListNode { Value = value, Next = null, Prev = null }; + Tail = Head; + + } private DoublyLinkedListNode? Traverse() @@ -66,17 +81,30 @@ namespace C_.Datastructures if (i > (Count/2)) { + //reverse direction of search direction = -1; node = Tail; - i = Count - i; + //i becomes the amount of hops left to reach the item + i = Count - i - 1; } if (node != null) { - //continue to end of list + + + + //continue to given point in the list ('i' hops) for (int x = 0; x < i; x++) { - //Incomplete Traverse Functions + if (direction == 1) + {//Going forwards + node = node!.Next; + } + else + { + node = node!.Prev; + } + } } return node; diff --git a/C#/Program.cs b/C#/Program.cs index 76989c1..57d8941 100644 --- a/C#/Program.cs +++ b/C#/Program.cs @@ -5,22 +5,18 @@ using C_.Datastructures.Nodes; // See https://aka.ms/new-console-template for more information Console.WriteLine("Hello, World!"); -LinkedList list = new(); +DoublyLinkedList list = new DoublyLinkedList(); -list.Append(1); -list.Append(2); -list.Append(3); +list.Add(1); +list.Add(2); +list.Add(3); +list.Add(4); +list.Add(5); +list.Add(6); +list.Add(7); +list.Add(8); -LinkedList list2 = new(); +var x = list[-6]; -list2.Append(1); -list2.Append(2); -list2.Append(3); +Console.WriteLine(x); - -LinkedList list3 = LinkedList.Create(list, list2); - -list3.Insert(4, 1); -list3.Delete(0); -list3.Head = LinkedListNode.Create(5, null); -Console.ReadLine(); \ No newline at end of file