Why are Stack and Queue implemented with an array?

前端 未结 3 1169
粉色の甜心
粉色の甜心 2020-12-01 12:24

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 res

3条回答
  •  忘掉有多难
    2020-12-01 12:35

    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).

提交回复
热议问题