Added delete method to doubly linked list

This commit is contained in:
Luke Else 2022-03-16 22:07:11 +00:00
parent 7ced980a90
commit 431785b586
3 changed files with 24 additions and 4 deletions

View File

@ -90,6 +90,26 @@ namespace C_.Datastructures
} }
public bool Delete(int index){
DoublyLinkedListNode<T>? node = Traverse(index);
if (node == default) return false;
if(node.Prev != default){
//connect item beofre to item after node we are deleting
node.Prev.Next = node.Next;
}
//Connect item after to the the item before the node we are deleting
if (node.Next != default)
{
node.Next.Prev = node.Prev;
}
Count--;
return true;
}
private DoublyLinkedListNode<T>? Traverse() private DoublyLinkedListNode<T>? Traverse()
{ {

View File

@ -144,14 +144,14 @@ namespace C_.Datastructures
// return node; // return node;
//} //}
private LinkedListNode<T>? Traverse(int n) private LinkedListNode<T>? Traverse(int i)
{ {
//Start at given point in list //Start at given point in list
LinkedListNode<T>? node = Head; LinkedListNode<T>? node = Head;
if (node != null || n == 0) if (node != null || i == 0)
{ {
//Continue to end of list //Continue to end of list
for (int i = 0; i < n; i++) for (int j = 0; j < i; j++)
{ {
if (node!.Next == null) return null; if (node!.Next == null) return null;
node = (LinkedListNode<T>)node.Next; node = (LinkedListNode<T>)node.Next;

View File

@ -27,7 +27,7 @@ list2.Add(6);
list2.Add(7); list2.Add(7);
list2.Add(8); list2.Add(8);
var list3 = DoublyLinkedList<int>.Create(list, null); list.Delete(2);
var x = list[-6]; var x = list[-6];