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#中删除不在堆栈顶部的堆栈项
基础教程推荐
- 在 VB6 或经典 ASP 中使用 .NET 2022-01-01
- 获取C#保存对话框的文件路径 2022-01-01
- 如果条件可以为空 2022-01-01
- C# 9 新特性——record的相关总结 2023-04-03
- SonarQube C# 分析失败“不是指针的有效行偏移" 2022-01-01
- 重新排序 WPF TabControl 中的选项卡 2022-01-01
- Mono https webrequest 失败并显示“身份验证或解密失败" 2022-01-01
- 从 C# 控制相机设备 2022-01-01
- 将数据集转换为列表 2022-01-01
- 更新 Visual Studio 中的 DataSet 结构以匹配新的 SQL 数据库结构 2022-01-01
