0ms c++ solution using two stacks STL


  • 1
    J

    class Queue {
    public:

    stack<int> s1;
    stack<int> s2;
    // Push element x to the back of queue.
    void push(int x) {
        s1.push(x);
        
    }
    
    // Removes the element from in front of queue.
    void pop(void) {
        if(s1.empty())
            return;
        while(!s1.empty())  {
            s2.push(s1.top());
            s1.pop();
        }
        s2.pop();
        while(!s2.empty()) {
            s1.push(s2.top());
            s2.pop();
        }
    }
    
    // Get the front element.
    int peek(void) {
        if(s1.empty())
            return -1;
         while(!s1.empty())  {
            s2.push(s1.top());
            s1.pop();
        }
        int t = s2.top();
        while(!s2.empty()) {
            s1.push(s2.top());
            s2.pop();
        }
        return t;
    }
    
    // Return whether the queue is empty.
    bool empty(void) {
        return s1.empty();
    }
    

    };


Log in to reply
 

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