Removing from a linked list C #

I am trying to remove node if x currently matches an int in my linked list.

I tried this, but as soon as it removes the node, it throws an error while checking the foreach loop

public void DeleteNode(int x, LinkedList<name> myLinkedList) { foreach (name item in myLinkedList) { if (item.num.equals(x)) mylinkedList.Remove(x); } } 

Hope this makes sense.

+4
source share
5 answers

Yes, you cannot iterate over a collection and modify it at the same time. However, LinkedList<T> makes iterating explicitly pretty easy:

 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 cannot leave just by taking node = node.Next; as the last line; node is invalid when deleting it.

This approach allows a single crawl of the list in O (n) and is probably the most efficient approach you will find. It does not require copying or working with a collection (say List<T> ) with less efficient removal complexity.

+19
source

If you call remove during foreach , this will invalidate the enumerator, so this is not allowed.

Change foreach to a simple for loop.

0
source

In this situation, I usually create a temporary collection and add it to it if it needs to be deleted. Then I look at this list, removing it from the original.

0
source

As I write that without canceling the iterator, this is:

 foreach(var item in list.Where(w=>w.num.Equals(x)).ToArray()) list.Remove(item); 
0
source

I remove items from the list as follows:

 for (int j = lst.Count - 1; j >= 0; j--) { var elem= lst[j]; lst.Remove(elem); } 

It looks very close to the regular "foreach var elem in lst", so I like it.

I go from end to start, otherwise you will lose your indexing and will track the number of deleted items.

0
source

All Articles