gpt4 book ai didi

c# - 为什么 System...Stack 不作为链表实现?

转载 作者:太空狗 更新时间:2023-10-29 23:57:58 25 4
gpt4 key购买 nike

我查看了我的代码,发现了一些我编写的扩展方法,用于从 System.Collections.Generic.Stack 中删除项目。我很好奇,所以我查看了 Stack with Reflector 的源代码,我可以看到他们将它实现为数组而不是链表,我只是想知道为什么?使用链表就不需要调整内部数组的大小...

这是我的扩展,欢迎任何批评或建议。谢谢。

public static Stack<T> Remove<T>(this Stack<T> stack, T item)
{
Stack<T> newStack = new Stack<T>();

EqualityComparer<T> eqc = EqualityComparer<T>.Default;

foreach( T newItem in stack.Reverse() )
{
if( !eqc.Equals(newItem, item) )
{
newStack.Push(newItem);
}
}

return newStack;
}
/// <summary>
/// Returns a new Stack{T} with one or more items removed, based on the given predicate.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="stack"></param>
/// <param name="fnRemove"></param>
/// <returns>The new stack.</returns>
/// <remarks>
/// We have to turn tricks in order to save the LIFO order of the pool
/// since there is no built-in remove method since they implement a Stack internally
/// as an array instead of a linked list. Maybe they have a good reason, I don't know...
///
/// So, to fix this I'm just using a LINQ extension method to enumerate in reverse.
/// </remarks>
public static Stack<T> RemoveWhere<T>(this Stack<T> stack, Predicate<T> fnRemove)
{
Stack<T> newStack = new Stack<T>();

foreach( T newItem in stack.Reverse() )
{
/// Check using the caller's method.
if( fnRemove(newItem) )
{
/// It's not allowed in the new stack.
continue;
}
newStack.Push(newItem);
}

return newStack;
}

最佳答案

后进先出队列(堆栈)通常对数组最有效,因为您将项目推到数组的末尾并从数组的同一端拉出项目。所以数组运行良好,没有链表的内存和分配开销。不需要创建和垃圾收集列表项包装器对象来抵消创建和调整数组大小的成本。

关于c# - 为什么 System...Stack<T> 不作为链表实现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/410417/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com