How to implement 3 stacks with one array?

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

    Partitioning the array into 3 parts in not a good idea as it will give overflow if there are many elements in stack1 and very few elements in the other two.

    My idea:

    Keep three pointers ptr1, ptr2, ptr3 to point the top element of respective stacks.

    Initially ptr1 = ptr2 = ptr3 = -1;

    In the array, the even indexed element will store the value and odd indexed element will store the index of previous element of that stack.

    For example,

    s1.push(1);
    s2.push(4);
    s3.push(3);
    s1.push(2);
    s3.push(7);
    s1.push(10);
    s1.push(5);
    

    then our array looks like:

    1, -1, 4, -1, 3, -1, 2, 0, 7, 4, 10, 6, 5, 10
    

    and the values of pointers are:

    ptr1 = 12, ptr2 = 2 , ptr3 = 8
    

提交回复
热议问题