How to remove a stack item which is not on the top of the stack in C#(如何在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#中删除不在堆栈顶部的堆栈项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在C#中删除不在堆栈顶部的堆栈项
				
        
 
            
        基础教程推荐
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
 - 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
 - 首先创建代码,多对多,关联表中的附加字段 2022-01-01
 - 错误“此流不支持搜索操作"在 C# 中 2022-01-01
 - 全局 ASAX - 获取服务器名称 2022-01-01
 - 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
 - JSON.NET 中基于属性的类型解析 2022-01-01
 - 如何动态获取文本框中datagridview列的总和 2022-01-01
 - 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
 - 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
 
    	
    	
    	
    	
    	
    	
    	
    	
						
						
						
						
						
				
				
				
				