How to implement 3 stacks with one array?

后端 未结 19 2519
迷失自我
迷失自我 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:20

    Store the stack in the area in such way when first stack goes into index 0, then 0+3=3, then 3+3=6...; the second one goes into indexes 1, 1+3=4, 4+3=7...; the the third one goes into indexes 2, 2+3=5, 5+3=8 So if we mark the first stack elements with a, as one with b and there with c we get: a1 b1 c1 a2 b2 c2 a3 b3 c3...

    There could be gaps but we always know the top indexes which are stored in 3-element topIndex array.

提交回复
热议问题