How to implement 3 stacks with one array?

后端 未结 19 2267
迷失自我
迷失自我 2021-01-29 18:44

Sometimes, I come across the following interview question: How to implement 3 stacks with one array ? Of course, any static allocation is not a solution.

19条回答
  •  抹茶落季
    2021-01-29 19:24

    Space (not time) efficient. You could:

    1) Define two stacks beginning at the array endpoints and growing in opposite directions.

    2) Define the third stack as starting in the middle and growing in any direction you want.

    3) Redefine the Push op, so that when the operation is going to overwrite other stack, you shift the whole middle stack in the opposite direction before Pushing.

    You need to store the stack top for the first two stacks, and the beginning and end of the third stack in some structure.

    Edit

    alt text

    Above you may see an example. The shifting is done with an equal space partitioning policy, although other strategies could be chosen depending upon your problem heuristics.

    Edit

    Following @ruslik's suggestion, the middle stack could be implemented using an alternating sequence for subsequent pushes. The resulting stack structure will be something like:

    | Elem 6 | Elem 4 | Elem 2 | Elem 0 | Elem 1 | Elem 3 | Elem 5 |

    In this case, you'll need to store the number n of elements on the middle stack and use the function:

    f[n_] := 1/4 ( (-1)^n (-1 + 2 n) + 1) + BS3  
    

    to know the next array element to use for this stack.

    Although probably this will lead to less shifting, the implementation is not homogeneous for the three stacks, and inhomogeneity (you know) leads to special cases, more bugs and difficulties to maintain code.

提交回复
热议问题