import java.util.Arrays; /** * divide the array into three stacks * @author Prateek */ class MakeThreeStacks { private int stackSize=5; private int[] tops={-1,-1,-1}; private int[] arr=new int[stackSize * 3]; /** * Push operation * @param stackNum : specifies the stack number * @return: insertion status * @throws InterruptedException */ if(stackNum==0 || stackNum==1 || stackNum==2){ int index= stackNum * stackSize + tops[stackNum] + 1; if(tops[stackNum] < stackSize -1 ){ tops[stackNum]++; arr[index]=item; return true; } else{ return false; } } else { return false; } } /** * Pop operation * @param stackNum: specifies the stack number * @return the poped item * @throws InterruptedException */ if(stackNum==0 || stackNum==1 || stackNum==2){ if(tops[stackNum]==-1) { return -1; } int index= stackNum * stackSize + tops[stackNum]; tops[stackNum]--; int item= arr[index]; arr[index]=0; return item; } else { return -9999; } } /** * Peek operation * @param stackNum: specifies the stack number * @return top element of the specified stack */ public int peek(int stackNum){ if(stackNum==0 || stackNum==1 || stackNum==2){ if(tops[stackNum]==-1) { return -1; } int index= stackNum * stackSize + tops[stackNum]; return arr[index]; } else { return -99999; } } MakeThreeStacks stack=new MakeThreeStacks(); stack.push(1, 1); stack.push(3, 2); stack.push(0, 3); stack.push(1, 4); stack.push(2, 5); stack.push(2, 6); stack.push(3, 7); stack.pop(0); stack.pop(1); stack.pop(0); stack.pop(2); } }
Standard input is empty
[0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0] Invalid Stack Number [3, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0] [3, 0, 0, 0, 0, 1, 4, 0, 0, 0, 0, 0, 0, 0, 0] [3, 0, 0, 0, 0, 1, 4, 0, 0, 0, 5, 0, 0, 0, 0] [3, 0, 0, 0, 0, 1, 4, 0, 0, 0, 5, 6, 0, 0, 0] Invalid Stack Number [0, 0, 0, 0, 0, 1, 4, 0, 0, 0, 5, 6, 0, 0, 0] [0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 5, 6, 0, 0, 0] [0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 5, 0, 0, 0, 0]
Stack is Empty