Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing from linked list C#

Tags:

c#

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.

like image 504
GodsCrimeScene Avatar asked Oct 07 '11 15:10

GodsCrimeScene


1 Answers

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.

like image 161
Jon Skeet Avatar answered Oct 20 '22 18:10

Jon Skeet