Saturday, November 28, 2015

Implementing 3 fixed size Stacks using same Array

public class ThreeStacks {
    int ArraySize;
    int[] Array;
    int[] topPointers =  {-1,-1,-1};
    public ThreeStacks(int size) {
        this.ArraySize = size;
        this.Array = new int[size * 3];
    }
    public int peek(int StackNumber)    {
        if(topPointers[StackNumber-1]>-1)    {
            return Array[(ArraySize*StackNumber)+topPointers[StackNumber]];
        }    else    {
            System.out.println("Error: "+StackNumber+" is empty");
            return ErrorCode;
        }
    }
    public static final int ErrorCode = -999;
    public int pop(int StackNumber)    {
        StackNumber--;
        if(topPointers[StackNumber]>-1)    {
            int ret = Array[(ArraySize*StackNumber)+topPointers[StackNumber]];
            topPointers[StackNumber]--;
            return ret;
        }    else    {
            System.out.println("Error: "+StackNumber+" is empty");
            return ErrorCode;
        }
    }
    public void push(int data, int StackNumber)    {
        int maxSize = (ArraySize*StackNumber)-1;
        if(topPointers[StackNumber-1]<maxSize)    {
            topPointers[StackNumber-1]++;
            int nextLoc = (ArraySize*(StackNumber-1))+topPointers[StackNumber-1];
            Array[nextLoc]=data;
        }    else    {
            System.out.println("Stack "+StackNumber+" is full");
        }
    }
    public void print3Stacks()    {
        StringBuffer sb =new StringBuffer();
        for(int i=0; i<=topPointers[0]; i++)    {
            sb.append(Array[i]);
        }
        System.out.println(sb.toString());
        sb =new StringBuffer();
        for(int i=ArraySize; i<=ArraySize+topPointers[1]; i++)    {
            sb.append(Array[i]);
        }
        System.out.println(sb.toString());
        sb =new StringBuffer();
        for(int i=(ArraySize*2); i<=(ArraySize*2)+topPointers[2]; i++)    {
            sb.append(Array[i]);
        }
        System.out.println(sb.toString());
    }
}
UA-39217154-2