Added Delete Method and updated Indexing Methods
This commit is contained in:
parent
02f49782ee
commit
8165bb849b
@ -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<T>? node = Traverse(index - 1);
|
||||
node!.Next = new Node<T> {
|
||||
Value = value,
|
||||
Next = node.Next
|
||||
};
|
||||
Count++;
|
||||
}
|
||||
|
||||
public void Delete(int index)
|
||||
{
|
||||
if (index == 0 && Head != null)
|
||||
{
|
||||
Head = (Node<T>?)Head!.Next;
|
||||
return;
|
||||
}
|
||||
|
||||
Node<T>? 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<T>? Traverse(){
|
||||
//Start at Head of list
|
||||
Node<T>? node = Head;
|
||||
@ -123,12 +153,12 @@ namespace C_.Datastructures
|
||||
{
|
||||
//Start at given point in list
|
||||
Node<T>? 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<T>)node.Next;
|
||||
}
|
||||
}
|
||||
|
@ -20,4 +20,6 @@ list2.Append(3);
|
||||
LinkedList<int> list3 = LinkedList<int>.Create(list, list2);
|
||||
|
||||
int x = list3[5] = 5;
|
||||
list3.Insert(4, 1);
|
||||
list3.Delete(0);
|
||||
Console.ReadLine();
|
Loading…
Reference in New Issue
Block a user