How to implement 3 stacks with one array?

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

    package job.interview; import java.util.Arrays;

    public class NStack1ArrayGen {
    
        T storage[];
        int numOfStacks;
        Integer top[];
        public NStack1ArrayGen(int numOfStks, T myStorage[]){
            storage = myStorage;
            numOfStacks = numOfStks;
            top = new Integer[numOfStks];
            for(int i=0;i " + value);
        }
        public void printStack(int indx){
            String str = "";
            while(top[indx-1]>=0){
                str+=(str.length()>0 ? "," : "") + pop(indx);
            }
            print("Stack#"+indx,str);
        }
        public static void main (String args[])throws Exception{
            int count=4, tsize=40;
            int size[]={105,108,310,105};
            NStack1ArrayGen mystack = new NStack1ArrayGen(count,new String[tsize]); 
            for(int i=1;i<=count;i++){
                for(int j=1;j<=size[i-1];j++){
                    mystack.push(i, "stk"+i+"_value"+j);
                }
            }
        }
    }
    

    This prints:

    The array ==> [stk1_value1, stk2_value1, stk3_value1, stk4_value1, stk1_value2, stk2_value2, stk3_value2, stk4_value2, stk1_value3, stk2_value3, stk3_value3, stk4_value3, stk1_value4, stk2_value4, stk3_value4, stk4_value4, stk1_value5, stk2_value5, stk3_value5, stk4_value5, stk1_value6, stk2_value6, stk3_value6, stk4_value6, stk1_value7, stk2_value7, stk3_value7, stk4_value7, stk1_value8, stk2_value8, stk3_value8, stk4_value8, stk1_value9, stk2_value9, stk3_value9, stk4_value9, stk1_value10, stk2_value10, stk3_value10, stk4_value10] The top indices ==> [36, 37, 38, 39] Stack#1 ==> stk1_value10,stk1_value9,stk1_value8,stk1_value7,stk1_value6,stk1_value5,stk1_value4,stk1_value3,stk1_value2,stk1_value1 Stack#2 ==> stk2_value10,stk2_value9,stk2_value8,stk2_value7,stk2_value6,stk2_value5,stk2_value4,stk2_value3,stk2_value2,stk2_value1 Stack#3 ==> stk3_value10,stk3_value9,stk3_value8,stk3_value7,stk3_value6,stk3_value5,stk3_value4,stk3_value3,stk3_value2,stk3_value1 Stack#4 ==> stk4_value10,stk4_value9,stk4_value8,stk4_value7,stk4_value6,stk4_value5,stk4_value4,stk4_value3,stk4_value2,stk4_value1

提交回复
热议问题