How to implement three stacks using a single array

后端 未结 17 609
情书的邮戳
情书的邮戳 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 16:05

    This is an interesting conundrum, and I don't have a real answer but thinking slightly outside the box...

    it could depend on what each element in the stack consists of. If it's three stacks of true/false flags, then you could use the first three bits of integer elements. Ie. bit 0 is the value for the first stack, bit 1 is the value for the second stack, bit 2 is the value for the third stack. Then each stack can grow independently until the whole array is full for that stack. This is even better as the other stacks can also continue to grow even when the first stack is full.

    I know this is cheating a bit and doesn't really answer the question but it does work for a very specific case and no entries in the stack are wasted. I am watching with interest to see whether anyone can come up with a proper answer that works for more generic elements.

提交回复
热议问题