Stack<Integer> stackA = newStack<>(); Stack<Integer> stackB = newStack<>(); //add a element to queue publicvoidpush1(int x){ if (stackA.empty()){ stackA.push(x); }else{ while (!stackA.empty()) stackB.push(stackA.pop()); stackA.push(x); while (!stackB.empty()) stackA.push(stackB.pop()); } } //remove the front element of the queue publicintpop1(){ if (!stackA.empty()) return stackA.pop(); return Integer.MIN_VALUE; } //print the front element of the queue, do not delete, just print publicvoidpeek1(){ if (!stackA.empty()) System.out.println(stackA.peek()); } //print the size of the queue publicvoidsize1(){ System.out.println(stackA.size()); } }
//push a data to the stack publicvoidpush2(int data) { if (stackA.empty() && !stackB.empty()) { while (!stackB.empty()) { stackA.push(stackB.pop()); } } //A is not empty, so push the data to A stackA.push(data); }
//get the size of the stack publicvoidsize2() { intlength=0; if (!stackA.empty()) while (!stackA.empty()) { stackA.pop(); length++; } elseif (!stackB.empty()) while (!stackB.empty()) { stackB.pop(); length++; } System.out.println(length); }
//remove the top element data publicvoidpop2() { if (stackA.empty() && stackB.empty())//都为空时 System.out.println("null"); elseif (!stackA.empty()){//执行pop之前的操作,都是push,此时栈B是空的 while (!stackA.empty()) stackB.push(stackA.pop()); stackB.pop(); }elseif (stackA.empty() && !stackB.empty())//上一步执行的pop操作,栈A是空的, stackB.pop(); }
//print the top element data publicvoidpeek2() { if (stackA.empty() && stackB.empty())//都为空时 System.out.println("null"); elseif (!stackA.empty()){//执行pop之前的操作,都是push,此时栈B是空的 while (!stackA.empty()) stackB.push(stackA.pop()); System.out.println(stackB.peek()); }elseif (stackA.empty() && !stackB.empty())//上一步执行的pop操作,栈A是空的, System.out.println(stackB.peek()); } }