How to implement three stacks using a single array

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

    Perhaps you can implement N number of stacks or queues in the single array. My defination of using single array is that we are using single array to store all the data of all the stacks and queues in the single array, anyhow we can use other N array to keep track of indices of all elements of particular stack or queue.

    solution : store data sequentially to in the array during the time of insertion in any of the stack or queue. and store it's respective index to the index keeping array of that particular stack or queue.

    for eg : you have 3 stacks (s1, s2, s3) and you want to implement this using a single array (dataArray[]). Hence we will make 3 other arrays (a1[], a2[], a3[]) for s1, s2 and s3 respectively which will keep track of all of their elements in dataArray[] by saving their respective index.

    insert(s1, 10) at dataArray[0] a1[0] = 0;
    insert(s2, 20) at dataArray[1] a2[0] = 1;
    insert(s3, 30) at dataArray[2] a3[0] = 2;
    insert(s1, 40) at dataArray[3] a1[1] = 3;
    insert(s3, 50) at dataArray[4] a3[1] = 4;
    insert(s3, 60) at dataArray[5] a3[2] = 5;
    insert(s2, 30) at dataArray[6] a2[1] = 6;
    

    and so on ...

    now we will perform operation in dataArray[] by using a1, a2 and a3 for respective stacks and queues.

    to pop an element from s1 return a1[0] shift all elements to left

    do similar approach for other operations too and you can implement any number of stacks and queues in the single array.

提交回复
热议问题