Queue: Implement queue using stacks

Problem Statement:

You need to implement queue using 2 stacks.

Solution Explanation:

we will use 2 stacks.

Below are the operations on how we do it:

Enqueue:

If s1 is not empty, move all the elements of s1 to s2.

Then push the element into s1

Then move everything back from s2 to s1

This will help to remain the front of the queue to be always on the top of s1.

Dequeue: Pop from the stack

Front: Top element from stack is always the top element.

Size: Return the size of the stack.

Code Solution

#include <iostream>
#include <vector>
#include <queue>
#include <stack>
using namespace std;

class myQueue 
{
    stack<int> s1, s2;

public:

    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()) 
        {
            
            return; 
        }
        
        s1.pop();
    }

    int front()
     {
        if (s1.empty()) 
        {
            
            return -1; 
        }
        return s1.top();
    }

    int size() 
    {
        return s1.size();
    }
};

int main() 
{
    myQueue q;
    q.enqueue(1);
    q.enqueue(2);
    q.enqueue(3);

    cout << "Front: " << q.front() << '\n';  
    cout << "Size: " << q.size() << '\n';    

    q.dequeue();              
    cout << "Front: " << q.front() << '\n';   
    cout << "Size: " << q.size() << '\n';    

    return 0;
}

 

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *