Reputation: 41
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)
Upvotes: 1
Views: 232
Reputation: 179
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);
}
Upvotes: 2
Reputation: 628
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);
}
Upvotes: 3