开发者

Removing from linked list 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 开发者_Go百科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 call remove during a foreach it will invalidate the enumerator, so this is not allowed.

Change your foreach to a simple for loop.


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


The way I write that, without invalidating the iterator, is:

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


I remove Items from list in the following way:

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

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

I go from the end to the beginning cause otherwise you'll loose your indexing, and will need to track number of removed items.


info is a class.

This will find through linkedlist and delete the first item who's no property value is 1

LinkedList<info> infolist = new LinkedList<info>();

string todelete = "1";

info tmpitem = new info();
foreach (var item in infolist)
{
    if (item.no == todelete)
        tmpitem = item;
}
infolist.Remove(tmpitem);


public ListNode RemoveElements(ListNode head, int val)
    {
    if (head == null) return null;
        head.next = RemoveElements(head.next, val);
        return head.val == val ? head.next : head;
        
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜