How to implement 3 stacks with one array?

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

    A variant on an earlier answer: stack #1 grows from the left, and stack #2 grows from the right.

    Stack #3 is in the center, but the elements grow in alternate order to the left and right. If N is the center index, the stack grows as: N, N-1, N+1, N-2, N+2, etc. A simple function converts the stack index to an array index.

提交回复
热议问题