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?
hmmmm...... I agree with the previous two answers but if you are looking to hack your way just pop and save all elements until you get to the one you want, and the re-push them all
Yes is ugly, badly performing, probably weird code that will need a long comment explaining why, but you could do it....
Consider using different container. Maybe a LinkedList. Then you can use
just like pop/push from stack and you can use
to remove any node from the middle of the list
If you need to remove items that aren't on the top, then you need something other than a stack.
Try making your own implementation of a stack from a List. Then you get to implement your own push and pop functions (add & remove on the list), and your own special PopFromTheMiddle function.
For example
Perhaps an extension method would work, although, I suspect that a different data structure entirely is really needed.
I used a list and added some extension methods, eg,