如何在C#中删除不在堆栈顶部的堆栈项 [英] How to remove a stack item which is not on the top of the stack in C#

查看:17
本文介绍了如何在C#中删除不在堆栈顶部的堆栈项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

不幸的是,一个项目只能通过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);
    }
}

这篇关于如何在C#中删除不在堆栈顶部的堆栈项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆