【14】Use a single array to implement three stacks

来源:互联网 发布:二次安防用哪个网络 编辑:程序博客网 时间:2024/05/29 13:34

Question:Describe how you could use a single array to implement three stacks.   

package CareerCup;public class OneArrayThreeStack {int[] array;int top1;int top2;int top3Left;int top3Right;boolean isLeft;public OneArrayThreeStack(int size){array = new int[size];top1 = 0;top2 = size-1;top3Left = size/2;top3Right = top3Left+1;isLeft = true;}public void push(int data,int type) throws Exception{if(type == 1){if(top1==top3Left+1)throw new Exception("The stack1 is full!");array[top1] = data;top1++;}else if(type == 2){if(top2==top3Right-1)throw new Exception("The stack2 is full!");array[top2] = data;top2--;}else if(type == 3){if(isLeft){if(top1-1==top3Left)throw new Exception("The stack3 is full!");array[top3Left] = data;top3Left--;}else{if(top2+1==top3Right)throw new Exception("The stack3 is full!");array[top3Right] = data;top3Right++;}isLeft = !isLeft;}}public int pop(int type) throws Exception{int res=-1;if(type == 1){if(top1==0)throw new Exception("The stack1 is empty!");res = array[--top1];array[top1] = 0;}else if(type == 2){if(top2==array.length-1)throw new Exception("The stack2 is empty!");res = array[++top2];array[top2] = 0;}else if(type == 3){if(top3Right == top3Left+1)throw new Exception("The stack3 is empty!");if(isLeft){res = array[--top3Right];array[top3Right] = 0;}else{res = array[++top3Left];array[top3Left] = 0;}}return res;}public void print(){System.out.print("Array:{");for(int i=0;i<array.length;i++)System.out.print(array[i]);System.out.print("}");System.out.println();}public void printValue(){System.out.println(top1+"\t"+top2+"\t"+top3Left+"\t"+top3Right+"\t"+isLeft);}public static void main(String[] args) throws Exception{int len = 9;OneArrayThreeStack ats = new OneArrayThreeStack(len);ats.push(1, 1);ats.printValue();ats.push(2, 2);ats.printValue();ats.push(3, 3);ats.printValue();ats.print();ats.push(1, 1);ats.printValue();ats.push(2, 2);ats.printValue();ats.push(3, 3);ats.printValue();ats.push(1, 1);ats.print();ats.printValue();ats.push(2, 2);ats.print();ats.printValue();ats.push(3, 3);ats.printValue();ats.print();ats.print();ats.pop(1);ats.printValue();ats.pop(2);ats.printValue();ats.pop(3);ats.printValue();ats.print();ats.pop(1);ats.printValue();ats.pop(2);ats.printValue();ats.pop(3);ats.printValue();ats.print();ats.pop(1);ats.printValue();ats.pop(2);ats.printValue();ats.pop(3);ats.printValue();ats.print();ats.print();}}


原创粉丝点击