简体   繁体   中英

Removing items from LinkedList<>

i have a linked list where i store item prices. I calculated the total sum of all the items and i want to check if the total price exceeds a set limit, if it does i want to remove items until it doesn't.

So my linked list looks like this

Name of item: Automobilis     |Amount of said item available: 1     | Amount needed: 1     | Total price of item/s: 3000
Name of item: Kirvis          |Amount of said item available: 50    | Amount needed: 2     | Total price of item/s: 200 
Name of item: Piesiniai       |Amount of said item available: 1     | Amount needed: 1     | Total price of item/s: 1800

 Total price of all items is: 5000

If i have a set limit of 4000, i want to remove items until it is less than that.

I am using this method to delete the node

static void DeleteNode(double x, LinkedList<MatchingItems> myLinkedList)
        {
            var node = myLinkedList.First;
            while (node != null)
            {
                var nextNode = node.Next;
               while (node.Value.FinalPrice > x)
                {
                    myLinkedList.Remove(node);
                }
                node = nextNode;
            }
        }

But when i try to run it it throws this error:

Unhandled Exception: System.InvalidOperationException: The LinkedList node does not belong to current LinkedList.
   at System.Collections.Generic.LinkedList`1.ValidateNode(LinkedListNode`1 node)
   at System.Collections.Generic.LinkedList`1.Remove(LinkedListNode`1 node)

The reason is you're using while to check if a node should be removed from the LinkedList or not at

while (node.Value.FinalPrice > x)
{
    myLinkedList.Remove(node);
}

the first node.Value.FinalPrice > x , it's removed from the LinkedList, and loop keeps going, and it tries to remove the node again and again, but it does not belong to the LinkedList anymore. Change it to

if (node.Value.FinalPrice > x)
{
    myLinkedList.Remove(node);
}

Error is because of while!you need to replace it with if because after the first loop there is no node anymore.

if (node.Value.FinalPrice > x)
 {
     myLinkedList.Remove(node);
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM