// use two stacks to simulate a queue Stack<Integer> stackIn; Stack<Integer> stackOut;
publicMyQueue() { stackIn = newStack<>(); stackOut = newStack<>(); } // stackIn's topside is the end of the queue publicvoidpush(int x) { stackIn.push(x); } // stackOut's topside is the head of the queue publicintpop() {
// if there is no element in the stackOut // fetch them from the stackIn if (stackOut.empty()) { while (!stackIn.empty()) { stackOut.push(stackIn.pop()); } } return stackOut.pop(); } // the easiest way to get the head element is pop it // then push it back to the head of the queue publicintpeek() { intans=this.pop(); stackOut.push(ans); return ans; } publicbooleanempty() { return stackIn.empty() && stackOut.empty(); } }
// let's cache the added element in our sub queue subDeque.offer(x);
// then move all the currently stored element into our sub queue while ( !storage_queue.isEmpty() ) { subDeque.offer(storage_queue.pollFirst()); }
// now the sub queue has a correct sequence as a stack // let's swap the two references Dequetemp= subDeque; subDeque = storage_queue; storage_queue = temp; } publicintpop() { return (Integer)storage_queue.pollFirst(); } publicinttop() { return (Integer)storage_queue.peekFirst(); } publicbooleanempty() { return storage_queue.isEmpty(); } }