Stack<Integer> instack = newStack<>(); Stack<Integer> outstack = newStack<>(); /** Initialize your data structure here. */ publicMyQueue() {
}
/** Push element x to the back of queue. */ publicvoidpush(int x) { while (!outstack.empty()) instack.push(outstack.pop()); instack.push(x); while (!instack.empty()) outstack.push(instack.pop()); }
/** Removes the element from in front of queue and returns that element. */ publicintpop() { return outstack.pop(); }
/** Get the front element. */ publicintpeek() { return outstack.peek(); }
/** Returns whether the queue is empty. */ publicbooleanempty() { return outstack.empty(); } }
classMyQueue { Stack<Integer> s1, s2; intsize=0; inttop=0; /** Initialize your data structure here. */ publicMyQueue() { s1 = newStack<>(); s2 = newStack<>(); } /** Push element x to the back of queue. */ publicvoidpush(int x) { s1.push(x); if (size == 0) top = x; size ++; } /** Removes the element from in front of queue and returns that element. */ publicintpop() { for (inti=0; i < size - 1; i ++) { if (i == size - 2) { top = s1.pop(); s2.push(top); } else s2.push(s1.pop()); } intelement= s1.pop(); size --; for (inti=0; i < size; i ++) s1.push(s2.pop()); return element; } /** Get the front element. */ publicintpeek() { return top; } /** Returns whether the queue is empty. */ publicbooleanempty() { return size == 0; } }