C++ 0ms solution using two stacks


  • 0
    I
    class Queue {
    public:
        stack<int> mystack1, mystack2;
        // Push element x to the back of queue.
        void push(int x) {
            mystack1.push(x);
        }
    
        // Removes the element from in front of queue.
        void pop(void) {
            //move all the elements from stack1 to stack2
            while(!mystack1.empty()){
                mystack2.push(mystack1.top());
                mystack1.pop();
            }
            //remove the desired element;
            mystack2.pop();
            //put the rest back from stack2 to stack1
            while(!mystack2.empty()){
                mystack1.push(mystack2.top());
                mystack2.pop();
            }
        }
    
        // Get the front element.
        int peek(void) {
            //move all the elements from stack1 to stack2
            while(!mystack1.empty()){
                mystack2.push(mystack1.top());
                mystack1.pop();
            }
            //remove the desired element;
            int temp = mystack2.top();
            //put the rest back from stack2 to stack1
            while(!mystack2.empty()){
                mystack1.push(mystack2.top());
                mystack2.pop();
            }
            return temp;
        }
    
        // Return whether the queue is empty.
        bool empty(void) {
            return mystack1.empty();
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.