How to implement a queue with three stacks?

前端 未结 5 1808
忘掉有多难
忘掉有多难 2020-12-12 08:51

I came across this question in an algorithms book (Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne).

Queue with three stacks. Implement

5条回答
  •  情书的邮戳
    2020-12-12 09:27

    You can do it in amortized constant time with two stacks:

    ------------- --------------
                | |
    ------------- --------------
    

    Adding is O(1) and removing is O(1) if the side you want to take from is not empty and O(n) otherwise (split the other stack in two).

    The trick is to see that the O(n) operation will only be done every O(n) time (if you split, e.g. in halves). Hence, the average time for an operation is O(1)+O(n)/O(n) = O(1).

    While this may seam like a problem, if you are using an imperative language with an array based stack (fastest), you are going to have only amortized constant time anyway.

提交回复
热议问题