Implement a Queue using Stack

This is the opposite of inserting a Stack using 2 queues. Here we are going to implement a Queue using Stacks. The main thing to remember here is that A queue has operations on both ends - Front and rear, and follow FIFO structure. 

Queue can be implemented using 2 stacks, Either we can make changes in the enqueue function or in the dequeue function, for this particular problem we are going to make changes to the Enqueue function so that->
  • while stack1 is not empty, push everything from stack1 to stack2
  • push x to stack1 
  • push everything back to stack1
  • time complexity will be O(n)
  • for dequeue() -> if stack1 is not empty, pop item from stack1 and return it 
  • time complexity for dequeue is O(1)   
Code-->

class queue{
    stack<int> s1, s2;
    
    void enqueue(int x)
    {
        while(!s1.empty())
            s2.push(s1.top());
            s1.pop():
    
       s1.push(x);
        while(!s2.empty())
            s1.push(s2.top());
            s2.pop();
    }
    
    void dequeue()
    {
        if(s1.empty())        
            cout<<Queue is empty";
            exit(0);
        int x= s1.top();
        s1.pop();
        return x;
    }
};

Popular posts from this blog

Finding the Subarrays (Hackerearth)

Palindrome Index (Hackerrank)

Sherlock and Array (Hackerrank)