如何在C#中删除不在堆栈顶部的堆栈项堆栈、如何在

由网友(大哥没感情)分享简介:不幸的是,一个项目只能通过pop"从堆栈中删除.堆栈没有删除"方法或类似的东西,但我有一个堆栈(是的,我需要一个堆栈!),我需要从中删除一些元素.Unfortunately an item can only be removed from the stack by "pop". The stack has no "r...

不幸的是,一个项目只能通过pop"从堆栈中删除.堆栈没有删除"方法或类似的东西,但我有一个堆栈(是的,我需要一个堆栈!),我需要从中删除一些元素.

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.

有什么诀窍吗?

推荐答案

如果您需要删除不在顶部的项目,那么您需要的不是堆栈.

If you need to remove items that aren't on the top, then you need something other than a stack.

尝试从列表中实现您自己的堆栈.然后您可以实现自己的推送和弹出功能(添加和删除列表),以及您自己的特殊 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);
    }
}
阅读全文

相关推荐

最新文章