如何以除去不上堆叠的顶部在C#堆栈项 [英] How to remove a stack item which is not on the top of the stack in C#
问题描述
不幸的是一个项目只能从堆栈中的弹出删除。堆栈没有删除的方法或类似的东西,但我有一个堆栈(是的,我需要一个堆栈!)从中我需要删除的一些元素。
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?
推荐答案
如果您需要删除不上顶级的项目,那么你需要东西比堆栈等。
If you need to remove items that aren't on the top, then you need something other than a stack.
尝试从列表制作自己的执行堆栈。然后你去实现自己的push和pop功能(添加和放大器;删除列表上),和自己的特殊PopFromTheMiddle功能
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.
例如
public class ItsAlmostAStack<T>
{
private List<T> items = new List<T>();
public void Push(T item)
{
items.Add(item);
}
public T Pop()
{
if (items.Count > 0)
{
T temp = items[items.Count - 1];
items.RemoveAt(items.Count - 1);
return temp;
}
else
return default(T);
}
public void Remove(int itemAtPosition)
{
items.RemoveAt(itemAtPosition);
}
}
这篇关于如何以除去不上堆叠的顶部在C#堆栈项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!