Formatted question description:

 232	Implement Queue using Stacks

 Implement the following operations of a queue using stacks.
     push(x) -- Push element x to the back of queue.
     pop() -- Removes the element from in front of queue.
     peek() -- Get the front element.
     empty() -- Return whether the queue is empty.


 MyQueue queue = new MyQueue();

 queue.peek();  // returns 1
 queue.pop();   // returns 1
 queue.empty(); // returns false


 You must use only standard operations of a stack -- which means only operations are valid
    push to top,
    peek/pop from top,
    size, and
    is empty

 Depending on your language, stack may not be supported natively.
 You may simulate a stack by using a list or deque (double-ended queue),
 as long as you use only standard operations of a stack.

 You may assume that all operations are valid
 (for example, no pop or peek operations will be called on an empty queue).



As long as the element is inserted from the front every time, for example, if a queue is 1, 2, 3, 4, then we save it in the stack as 4, 3, 2, 1, and then return to the top element 1, also It is the first element of the queue.

The difficulty of this question is the push function. We need an auxiliary stack tmp, and store the elements of s into tmp in reverse order. At this time, add a new element x, and then store the elements in tmp back. This is the order we want , The other three operations also directly call stack operations.

To optimize above, because every time you push, you have to flip both stacks,

So, have stacks new and old, the new pushed elements are cached in _new first, and all elements in _new are moved to _old only when the operations are pop and peek, which improves efficiency.



public class Implement_Queue_using_Stacks {
    class MyQueue {
        private Stack<Integer> stack1;
        private Stack<Integer> stack2;

        public MyQueue() {
            this.stack1 = new Stack<Integer>();
            this.stack2 = new Stack<Integer>();
        // Push element x to the back of queue.
        public void push(int x) {

        // Removes the element from in front of queue.
        public int pop() {
            if (!stack2.isEmpty()) {
                return stack2.pop(); // stack is queue-order, queue-head at this-stack-top
            } else {
                while (!stack1.isEmpty()) {
                return stack2.pop();

        // Get the front element.
        public int peek() {
            int ret = 0;
            if (!stack2.isEmpty()) {
                ret = stack2.peek();
            } else {
                while (!stack1.isEmpty()) {
                ret = stack2.peek();

            return ret;

        // Return whether the queue is empty.
        public boolean empty() {
            return stack1.isEmpty() && stack2.isEmpty();

All Problems

All Solutions