Implementation of Queue using Two Stacks in C++

Implementation of Queue using Two Stacks

Implementation of Queue using Two Stacks – Queue and stack are fundamentally two different linear data structures, but given with one or more of any one data structures, we can just convert it into other and apply it in real. This article is about the Implementation of Queue using Two Stacks with the help of a Queue named class and two stacks inside it as member variables. 

Implementation of queue using two stacks in cpp

Stack vs Queue?

Stack is a data structure where you get Last in First out implementation, and queue is with first in first out implementation.

So, it seems impossible to turn a stack into a queue. Though by basic using of two stacks we can implement a queue very easily : Queue By 2 stacks.

What is Queue Using Two Stacks?

A Queue using two stacks is a technique where we simulate the behavior of a queue with the help of two stack data structures. Since stacks work in reverse order, the trick is to use two stacks to reverse the order twice — making it act like a queue.

There are two main methods to implement this:

  • Method 1: Making Enqueue Operation Costly
  • Method 2: Making Dequeue Operation Costly

The Algorithm to create a Queue using two Stacks

Here we are going to discuss the algorithm of how we can make a queue using just two stacks. To visualise it more clearly here a class with the name “Queue” has been created, where there will be just two stacks as member variables and the member functions will be working as the functions to access or manipulate the queue. We will use the stack in C++ STl as the stack.

  • So, we take two stacks, s1 and s2.
    s1 will be working as the main queue and s2 will help us in reversing the order of s1.
  • The basic difference between a stack and a queue is the popping process, that is called Dequeue for the queue. If you think the top of the stack is the back of the queue, the pushing process is the same. But the popping will be in the reverse order. So we will use a stack (s2) temporarily to reverse the values.
  • So, the pushing will be pushing to s1.
  • To pop elements from the back, we will pop out elements from s1 and push it in s2.
  • Then pop only one element.
  • Then again push them into s1. The order of them won’t change for the queue.
  • Same algorithm will be used to check the front value of the queue.

There is another way in which you can turn one stack into a queue. Here it is: Queue using one stack.

The code to implement this:

Run
#include<bits/stdc++.h>
using namespace std;

class Queue
{
public:
  stack< int> s1, s2;
  void Push (int i)
  {
    cout << "Pushing the element : " << i << endl;
    s1.push (i);
  }
  int pop ()
  {
    if (s1.empty ())
    {
	  cout << "The queue is empty" << endl;
	  return -1;
    }
    while (!s1.empty ())
    {
	  s2.push (s1.top ());
	  s1.pop ();
    }
    int b = s2.top ();
    s2.pop ();
    cout << "Popping the element : " << b << endl;
    while (!s2.empty ())
    {
	  s1.push (s2.top ());
	  s2.pop ();
    }
    return b;
  }
  void Show ()
  {
    while (!s1.empty ())
    {
	  s2.push (s1.top ());
	  s1.pop ();
    }
    while (!s2.empty ())
    {
	  cout << s2.top () << " ";
	  s1.push (s2.top ());
	  s2.pop ();
    }
  }
  int front ()
  {
    if (s1.empty ())
    {
	  cout << "The queue is empty" << endl;
	  return -1;
    }
    while (!s1.empty ())
    {
	  s2.push (s1.top ());
	  s1.pop ();
    }
    int b = s2.top ();
    while (!s2.empty ())
    {
	  s1.push (s2.top ());
	  s2.pop ();
    }
    return b;
  }
};

int main ()
{
  Queue q;
  q.Push (1);
  q.Push (5);
  q.Push (2);
  q.Push (11);
  cout << "The Queue now is : ";
  q.Show ();
  cout << endl;
  cout << "The front value right now is : " << q.front () << endl;
  q.pop ();
  q.pop ();
  q.Push (12);
  q.Push (8);
  cout << "The front value right now is : " << q.front () << endl;
  cout << "The Queue now is : ";
  q.Show ();
  cout << endl;
}

Output

Pushing the element : 1
Pushing the element : 5
Pushing the element : 2
Pushing the element : 11
The Queue now is : 1 5 2 11 
The front value right now is : 1
Popping the element : 1
Popping the element : 5
Pushing the element : 12
Pushing the element : 8
The front value right now is : 2
The Queue now is : 2 11 12 8

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Operations Involved in Queue Using Two Stacks

Just like a normal queue, the following operations are performed:

  • Enqueue(x): Add an element x to the rear of the queue.
  • Dequeue(): Remove an element from the front of the queue.
  • isEmpty(): Check whether the queue is empty.

Problem Description

Problem:
Implement a Queue using two stacks in C++. Your code should support the basic queue operations: enqueue, dequeue, and isEmpty.

Constraints:

  • Only standard stack operations like push(), pop(), top(), and empty() are allowed.
  • Use only two stacks.

Method 1: Making Enqueue Operation Costly

C++ Code

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

class Queue {
    stack s1, s2;

public:
    void enqueue(int x) {
        // Move all elements from s1 to s2
        while (!s1.empty()) {
            s2.push(s1.top());
            s1.pop();
        }

        // Push item into s1
        s1.push(x);

        // Push everything back to s1
        while (!s2.empty()) {
            s1.push(s2.top());
            s2.pop();
        }
    }

    int dequeue() {
        if (s1.empty()) {
            cout << "Queue is empty\n";
            return -1;
        }

        int x = s1.top();
        s1.pop();
        return x;
    }

    bool isEmpty() {
        return s1.empty();
    }
};

int main() {
    Queue q;
    q.enqueue(10);
    q.enqueue(20);
    q.enqueue(30);
    cout << "Dequeued: " << q.dequeue() << endl;
    cout << "Dequeued: " << q.dequeue() << endl;
    return 0;
}

Output:

Dequeued: 10
Dequeued: 20

Explanation of the Code

  • Before inserting, we reverse the entire stack (s1 to s2), push the new element, and reverse it back.
  • Dequeue becomes fast because front is always on top.

Method 2: Making Dequeue Operation Costly

C++ Code

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

class Queue {
    stack s1, s2;

public:
    void enqueue(int x) {
        s1.push(x);
    }

    int dequeue() {
        if (s1.empty() && s2.empty()) {
            cout << "Queue is empty\n";
            return -1;
        }

        // Move elements to s2 only when s2 is empty
        if (s2.empty()) {
            while (!s1.empty()) {
                s2.push(s1.top());
                s1.pop();
            }
        }

        int x = s2.top();
        s2.pop();
        return x;
    }

    bool isEmpty() {
        return s1.empty() && s2.empty();
    }
};

int main() {
    Queue q;
    q.enqueue(5);
    q.enqueue(15);
    q.enqueue(25);
    cout << "Dequeued: " << q.dequeue() << endl;
    cout << "Dequeued: " << q.dequeue() << endl;
    return 0;
}

Output:

Dequeued: 5
Dequeued: 15

Explanation of the Code

  • Enqueue is easy (just push into s1).
  • For dequeue, we reverse the elements only when s2 is empty.

Conclusion

Implementing a queue using two stacks in C++ is a classic data structure interview question. It tests your understanding of stacks, queues, and algorithmic thinking. Depending on the use-case, you can choose either method, making enqueue or dequeue costly.

FAQs - Queue using Two Stacks in C++

FAQs - Queue using Two Stacks in C++

A stack follows the Last In First Out (LIFO) rule, but a queue follows First In First Out (FIFO). Since stack and queue behave oppositely, we use two stacks together to simulate a queue. The first stack stores elements as they come in, and the second stack helps reverse the order when needed, so the element that came in first can also be the one that goes out first, just like a normal queue.

It depends on how your program is expected to behave:

  • If your program enqueues more frequently and dequeues less, go with costly dequeue. Here, enqueue is fast (just a push), but dequeue takes time only occasionally.
  • If your program needs fast dequeue operations, like in real-time processing or streaming, use costly enqueue, where all the heavy work is done during insertion.

In short:

  • Costly enqueue = Fast dequeue
  • Costly dequeue = Fast enqueue

No, a single stack is not sufficient to simulate the full behavior of a queue. Since a single stack only allows access to the most recently added item, there’s no direct way to access the “first inserted element” as a queue would require. We need two stacks to reverse the order of elements and maintain the FIFO behavior of a queue.

If we try to remove an item when both stacks are empty, it means the queue has no elements. In such cases, the program should:

  • Return a meaningful message like “Queue is empty” and
  • Avoid crashing or accessing invalid memory.

Handling such edge cases is important to make the program robust and user-friendly.

Yes, This concept is more than just academic. It’s used in:

  • Task scheduling systems where tasks arrive and are processed in order.
  • Undo-redo operations in editors (where two stacks help reverse operations).
  • Message queues or data buffering in software systems where incoming and outgoing data must be handled in order.
    Understanding this logic also helps in mastering more advanced topics like queues with constraints, or priority queues.

Yes, it is memory efficient enough for practical use. Although we use two stacks, the total number of elements stored is the same as in a normal queue — just temporarily split between two stacks. There’s no duplication of data. The only extra cost is some temporary storage and computation when transferring between the stacks, which is acceptable for most applications.

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription

Stacks

  • Introduction to Stack in Data Structure
    Click Here
  • Operations on a Stack
    Click Here
  • Stack: Infix, Prefix and Postfix conversions
    Click Here
  • Stack Representation in –
    C | C++ | Java
  • Representation of a Stack as an Array. –
    C | C++ | Java
  • Representation of a Stack as a Linked List. –
    C | C++ | Java
  • Infix to Postfix Conversion –
    C | C++ | Java
  • Infix to prefix conversion in –
    C | C++ | Java
  • Postfix to Prefix Conversion in –
    C | C++ | Java

Queues

  • Queues in Data Structures (Introduction)
    Click Here
  • Queues Program in C and implementation
    Click Here
  • Implementation of Queues using Arrays | C Program
    Click Here
  • Types of Queues in Data Structure
    Click Here
  • Application of Queue Data Structure
    Click Here
  • Insertion in Queues Program (Enqueuing) –
    C | C++ | Java
  • Deletion (Removal) in Queues Program(Dequeuing) –
    C | C++ | Java
  • Reverse a Queue –
    C | C++ | Java
  • Queues using Linked Lists –
    C | C++ | Java
  • Implement Queue using Stack –
    C | C++ | Java
  • Implement Queue using two Stacks –
    C | C++ | Java

Circular Queues

Priority Queue

  • Application of Priority Queue
  • Priority Queue Example
  • Priority Queue Introduction –
    C | C++ | Java
  • Priority Queue Implementation using Array –
    C | C++ | Java
  • Priority Queue using Linked List –
    C | C++ | Java
  • Priority Queue Insertion and Deletion-
    C | C++ | Java

Stacks

Queues

Circular Queues

Priority Queue

  • Application of Priority Queue
  • Priority Queue Example
  • Priority Queue Introduction – C | C++ | Java
  • Priority Queue Implementation using Array – C | C++ | Java
  • Priority Queue using Linked List – C | C++ | Java
  • Priority Queue Insertion and Deletion- C | C++ | Java