How to implement three stacks using a single array

后端 未结 17 607
情书的邮戳
情书的邮戳 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:55

    We can use long bit array representing to which stack the i-th array cell belongs to. We can take values by modulo 3 (00 - empty, 01 - A, 10 - B, 11 - C). It would take N/2 bits or N/4 bytes of additional memory for N sized array.

    For example for 1024 long int elements (4096 bytes) it would take only 256 bytes or 6%.

    This bit array map can be placed in the same array at the beginning or at the end, just shrinking the size of the given array by constant 6%!

提交回复
热议问题