Implement Queue using Stacks

Implementation:

This is implemented using two stack: Insertion : - O(1) Deletion:- O(n)

class MyQueue {
public:
    /** Initialize your data structure here. */
    stack<int> i;
    stack<int> d;
    MyQueue() {
 
    }
    
    /** Push element x to the back of queue. */
    void push(int x) {
        i.push(x);
    }
    
    /** Removes the element from in front of queue and returns that element. */
    int pop() {
        int k;
        while(!i.empty()){
           k = i.top();
            d.push(k);
            i.pop();
        }
        
        int res = d.top();
        d.pop();
        
         while(!d.empty()){
             k = d.top();
            i.push(k);
            d.pop();
        }
        
        return res;
       
    }
    
    /** Get the front element. */
    int peek() {
        int k;
        while(!i.empty()){
            k = i.top();
            d.push(k);
            i.pop();
        }
        
        int res = d.top();
        
         while(!d.empty()){
             k = d.top();
            i.push(k);
            d.pop();
        }
        
        return res;
    }
    
    /** Returns whether the queue is empty. */
    bool empty() {
        if(i.empty()){
            return true;
        }
        return false;
    }
};

Last updated