From 8165bb849b7be810edae76150051c6fadba194b9 Mon Sep 17 00:00:00 2001 From: Luke Else Date: Fri, 4 Mar 2022 10:49:08 +0000 Subject: [PATCH] Added Delete Method and updated Indexing Methods --- C#/Datastructures/LinkedList.cs | 34 +++++++++++++++++++++++++++++++-- C#/Program.cs | 2 ++ 2 files changed, 34 insertions(+), 2 deletions(-) diff --git a/C#/Datastructures/LinkedList.cs b/C#/Datastructures/LinkedList.cs index e8b6785..0cedaf4 100644 --- a/C#/Datastructures/LinkedList.cs +++ b/C#/Datastructures/LinkedList.cs @@ -91,6 +91,36 @@ namespace C_.Datastructures }; } + public void Insert(int index, T value) + { + if (index > Count) throw new System.Exception("Error! Index outside of Bounds"); + + //Fetch point in list at which item will be added + Node? node = Traverse(index - 1); + node!.Next = new Node { + Value = value, + Next = node.Next + }; + Count++; + } + + public void Delete(int index) + { + if (index == 0 && Head != null) + { + Head = (Node?)Head!.Next; + return; + } + + Node? 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--; + + } + private Node? Traverse(){ //Start at Head of list Node? node = Head; @@ -123,12 +153,12 @@ namespace C_.Datastructures { //Start at given point in list Node? node = Head; - if (node != null) + if (node != null || n == 0) { //Continue to end of list for (int i = 0; i < n; i++) { - if (node.Next == null) return null; + if (node!.Next == null) return null; node = (Node)node.Next; } } diff --git a/C#/Program.cs b/C#/Program.cs index 7c91549..a451da0 100644 --- a/C#/Program.cs +++ b/C#/Program.cs @@ -20,4 +20,6 @@ list2.Append(3); LinkedList list3 = LinkedList.Create(list, list2); int x = list3[5] = 5; +list3.Insert(4, 1); +list3.Delete(0); Console.ReadLine(); \ No newline at end of file