Program to Implement Stack using two Queues in Data Structures (C plus plus)

Program to Implement Stack using two Queues in Data Structures (C plus plus)

In this tutorial, we will learn about the Program to Implement Stack using two Queues in Data Structures (C plus plus).

/*C++ Program to Implement Stack using Two Queues*/

#include<iostream>

using namespace std;

struct queue1
{
    queue1 *next1;
    int d1;
}
*front1 = NULL, *rear1 = NULL, *q1 = NULL, *p1 = NULL, *np1 = NULL;

struct queue2
{
    queue2 *next2;
    int d2;
}
*front2 = NULL, *rear2 = NULL, *q2 = NULL, *p2 = NULL, *np2 = NULL;

void enqueue_1(int x)
{     
    np1 = new queue1;
    np1->d1 = x;
    np1->next1 = NULL;
    if (front1 == NULL)
    {
        rear1 = np1;
        rear1->next1 = NULL;
        front1 = rear1;
    }
  
    else
    {
        rear1->next1 = np1;
        rear1 = np1;
        rear1->next1 = NULL;
    }
}

int dequeue_1()
{
    int x;
    if (front1 == NULL)
    {
        cout<<"Queue is Empty "<<endl;
    }

    else
    {
        q1 = front1;
        front1 = front1->next1;
        x = q1->d1;
        delete(q1);
        return x;
    }
}

void enqueue_2(int x)
{
    np2 = new queue2;
    np2->d2 = x;
    np2->next2 = NULL;
    if (front2 == NULL)
    {
        rear2 = np2;
        rear2->next2 = NULL;
        front2=rear2;
    }

    else
    {
        rear2->next2 = np2;
        rear2 = np2;
        rear2->next2 = NULL;
    }
}

int dequeue_2()
{
    int x;
    if (front2 == NULL)
    {
        cout<<"Queue is empty "<<endl;
    }

    else
    {
        q2 = front2;
        front2 = front2->next2;
        x = q2->d2;
        delete(q2);
        return x;
    }
}        

int main()
{
    int num, val, s = 0;
    cout<<"Please enter the no of elements to be entered into stack: "<<endl;
    cin>>num;
    while (s < num)
    {
        cout<<"Please enter the desired values to be entered: "<<endl;
        cin>>val;
        enqueue_1(val);
        s++;
    }

    cout<<endl<<"Elements deleted "<<endl;

    while (front1 != NULL || front2 != NULL)
    {
        if (front2 == NULL)
        {
            while (front1->next1 != NULL)
            {
                enqueue_2(dequeue_1());
            }
            cout<<dequeue_1()<<endl;
        }
        
        else if (front1 == NULL)
        {
            while (front2->next2 != NULL)
            {
                enqueue_1(dequeue_2());
            }
            cout<<dequeue_2()<<endl;
        }
    }
    
}

Output:

rogram to Implement Stack using two Queues in Data Structures (C plus plus)
Program to Implement Stack using two Queues in Data Structures (C plus plus)
Prof.Fazal Rehman Shamil (Available for Professional Discussions)
1. Message on Facebook page for discussions,
2. Video lectures on Youtube
3. Email is only for Advertisement/business enquiries.