Unfortunately an item can only be removed from the stack by "pop". The stack has no "remove" method or something similar, but I have a stack (yes I need a stack!) from which I need to remove some elements between.
Is there a trick to do this?
Unfortunately an item can only be removed from the stack by "pop". The stack has no "remove" method or something similar, but I have a stack (yes I need a stack!) from which I need to remove some elements between.
Is there a trick to do this?
I came across this question. In my code I created my own extension method:
And I call my method like this:
In a true stack, this can only be done one way -
Pop all of the items until you remove the one you want, then push them back onto the stack in the appropriate order.
This is not very efficient, though.
If you truly want to remove from any location, I'd recommend building a pseudo-stack from a List, LinkedList or some other collection. This would give you the control to do this easily.
Then it is not a stack right? Stack is
LAST in FIRST out
. You will have to write a custom one or choose something else.The constructor of a Stack<> takes IEnumerable<> as a parameter. So it would be possible to perform the following:
This is non performant in a number of ways.
A trick I use in hairy situations is adding a 'deprecated' flag to the items in the stack. When I want to 'remove' an item, I simply raise that flag (and clean up any resources that are taken by the object). Then when Pop()ing items I simply check if the flag is raised, and pop again in a loop until a non-deprecated item is found.
You can manage your own item-count to know how many 'real' items are still in the queue, and obviously locking should be employed if this is required for multi-threaded solution.
I found that for queues that have constant flow through them - items pushed and popped - it's much more efficient to hanle it this way, its the fastest you can get (paying O(1) for removing an item from the middle) and memory wise if the object that is retained is small, it's mostly irrelevant if the items flow in a reasonable pace.
You could use a LinkedList
List based removal will likely be less efficient. In removal by reference List based stacks will have O(N) search and O(N) resizing. LinkedList search is O(N) and removal is O(1). For removal by index, LinkedList should have O(N) traversal and O(1) removal, while List will have O(1) traversal (because it is indexing) and O(N) removal due to resizing.
Besides efficiency, a LinkedList implementation will keep you in the standard library, opening your code to more flexibility and have you writing less.
This should be able to handle Pop, Push, and Remove