diff --git a/DataStructures/Graphs/UndirectedSparseGraph.cs b/DataStructures/Graphs/UndirectedSparseGraph.cs
index 3593c0ec..8f4e5d4e 100644
--- a/DataStructures/Graphs/UndirectedSparseGraph.cs
+++ b/DataStructures/Graphs/UndirectedSparseGraph.cs
@@ -236,19 +236,16 @@ public virtual bool RemoveVertex(T vertex)
if (!_adjacencyList.ContainsKey(vertex))
return false;
- _adjacencyList.Remove(vertex);
-
- foreach (var adjacent in _adjacencyList)
+ var neighbors = Neighbours(vertex);
+ foreach (var neighbor in neighbors)
{
- if (adjacent.Value.Contains(vertex))
- {
- adjacent.Value.Remove(vertex);
-
- // Decrement the edges count.
- --_edgesCount;
- }
+ _adjacencyList[neighbor].Remove(vertex);
}
+ _edgesCount -= neighbors.Count;
+
+ _adjacencyList.Remove(vertex);
+
return true;
}
diff --git a/DataStructures/Lists/DLinkedList.cs b/DataStructures/Lists/DLinkedList.cs
index e2fa6a1a..8dfe83f1 100644
--- a/DataStructures/Lists/DLinkedList.cs
+++ b/DataStructures/Lists/DLinkedList.cs
@@ -557,14 +557,7 @@ public virtual void Clear()
/// True if found; false otherwise.
public virtual bool Contains(T dataItem)
{
- try
- {
- return Find(dataItem).IsEqualTo(dataItem);
- }
- catch (Exception)
- {
- return false;
- }
+ return TryFind(dataItem, out var found) && found.IsEqualTo(dataItem);
}
///
@@ -589,6 +582,33 @@ public virtual T Find(T dataItem)
throw new Exception("Item was not found.");
}
+ ///
+ /// Tries to find the specified item in the list.
+ ///
+ /// Value to find.
+ /// Value if found, default otherwise.
+ /// value.
+ public virtual bool TryFind(T dataItem, out T found)
+ {
+ found = default;
+
+ if (IsEmpty()) return false;
+
+ var currentNode = _firstNode;
+ while (currentNode != null)
+ {
+ if (currentNode.Data.IsEqualTo(dataItem))
+ {
+ found = dataItem;
+ return true;
+ }
+
+ currentNode = currentNode.Next;
+ }
+
+ return false;
+ }
+
///
/// Tries to find a match for the predicate. Returns true if found; otherwise false.
///