I'm trying to delete a node, if x currently matches a int in my linked list.
I tried this, but once it removes the node it throws an error when examining foreach loop
public void DeleteNode(int x, LinkedList<name> myLinkedList) {
foreach (name item in myLinkedList) {
if (item.num.equals(x)) mylinkedList.Remove(x);
}
}
Hope that makes sense.
Yes, you can't iterate over a collection and modify it at the same time. However, LinkedList<T>
lets you do the iteration explicitly pretty easily:
public void DeleteNode(int x, LinkedList<name> myLinkedList) {
var node = myLinkedList.First;
while (node != null) {
var nextNode = node.Next;
if (node.Value.num == x) {
myLinkedList.Remove(node);
}
node = nextNode;
}
}
Note that you can't get away with just taking node = node.Next;
as the last line; the node is invalidated when it's removed.
This approach allows a single traversal of the list in O(n), and is likely to be the most efficient approach you'll find. It doesn't require any copying, or working with a collection (say List<T>
) with less efficient removal complexity.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With