How to implement three stacks using a single array

后端 未结 17 798
情书的邮戳
情书的邮戳 2020-12-23 15:10

I came across this problem in an interview website. The problem asks for efficiently implement three stacks in a single array, such that no stack overflows until there is no

17条回答
  •  星月不相逢
    2020-12-23 15:39

    A rather silly but effective solution could be:

    • Store the first stack elements at i*3 positions: 0,3,6,...
    • Store the second stack elements at i*3+1 positions: 1,4,7...
    • And third stack elements at i*3+2 positions.

    The problem with this solution is that the used memory will be always three times the size of the deepest stack and that you can overflow even when there are available positions at the array.

提交回复
热议问题