为什么堆栈< T>和队列< T>一个数组实现的?堆栈、队列、数组、GT

2023-09-02 01:57:15 作者:枪打天下

我读果壳中的C#4.0的阿尔巴哈利兄弟我碰到这样的:

  

堆栈都与一个数组多数民众赞成调整的要求,与队列和List内部实现。 (第288条第4款)

我不禁想知道为什么。链表提供了O(1)头部和尾部插入和删除(这应该工作以及堆栈或队列)。一个大小可调整的阵列具有O(1)摊销插入(如果我没记错的话),但为O(n)最坏的情况(我不知道删除)。它可能比使用链表更多的空间(大叠/队列)。

有没有更多的原因呢?什么是缺点双向链表实现?

解决方案   

但为O(n)最坏的情况下

在摊销最坏的情况下的仍然是O(1)。多空插入时间平均掉 - 这是整点摊销分析(与同为删除)

这是数组也使用的少的空间比链表(这毕竟能够存储额外的指针每个元素)。

此外,开销比用链表只是要少得多。总而言之,基于阵列的实现仅仅是(多)多为几乎所有用例有效,即使偶尔的访问将需要更长的时间(事实上,一个队列可以稍微更有效地采取实施利用这一点是自己在一个链表管理页面 - 见C ++ 的std :: deque的实施)

I'm reading C# 4.0 in a Nutshell by the Albahari brothers and I came across this:

业绩高速增长的背后,爱美客到底具备哪些优势

Stacks are implemented internally with an array that's resized as required, as with Queue and List. (pg 288, paragraph 4)

I can't help but wonder why. LinkedList provides O(1) head and tail inserts and deletes (which should work well for a stack or queue). A resizable array has O(1) amortized insert (if I remember right), but O(n) worst case (I'm not sure about delete). And it probably uses more space than the linked list (for large stacks/queues).

Is there more to it than that? What is the downside to a doubly linked list implementation?

解决方案

but O(n) worst case

The amortized worst case is still O(1). Long and short insertion times average out – that’s the whole point of amortised analysis (and the same for deletion).

An array also uses less space than a linked list (which after all has to store an additional pointer for each element).

Furthermore, the overhead is just much less than with a linked list. All in all, an array-based implementation is just (much) more efficient for almost all use-cases, even though once in a while an access will take a little longer (in fact, a queue can be implemented slightly more efficiently by taking advantage of pages that are themselves managed in a linked list – see C++’ std::deque implementation).