To implement Stack using Two Queues in C++

In this tutorial, we will learn how to implement stack using queues in C++. Let us start with the algorithm.

Algorithm: Stack using two queues in C++

  1. When calling the push function, simply enqueue the elements into the queue 1.
  2. If it call pop function
  3. Deque all the elements from queue 1 and enqueue into queue 2 except the recently enqueued element of queue 1.
  4. Now deque recently inserted element from queue 1 and display it.
  5. Deque all elements of queue 2 and enqueue into queue 1.

Program in C++

#include<iostream>
#include<stdlib.h>
#define maxsize 20
using namespace std;
int rear1=-1, front1=-1, queue1[maxsize];
int rear2=-1, front2=-1, queue2[maxsize];
void insertion1(int ele)
{
  rear1=rear1+1;
  queue1[rear1]=ele;
  if(front1==-1)
  {
    front1=0;
  }
}
int deletion1()
{
  int x;
  x=queue1[front1];
  if(front1==rear1)
  {
    front1=rear1=-1;
  }
  else
  {
    front1++;
  }
  return x;

}
void insertion2(int ele)
{
  rear2++;
  queue2[rear2]=ele;
  if(front2==-1)
  {
    front2=0;
  }
}
int deletion2()
{
  int x;
  x=queue2[front2];
  if(front2==rear2)
  {
    front2=rear2=-1;
  }
  else
  {
    front2++;
  }
  return x;

}
void push()
{
  int ele;
  cout<<"Enter element to be insert: ";
  cin>>ele;
  insertion1(ele);

}
void pop()
{
  int x;
  while(front1!=rear1)
  {
    x=deletion1();
    insertion2(x);
  }
  x=deletion1();
  cout<<x;
  while(front2!=-1)
  {
    x=deletion2();
    insertion1(x);
  }
}
void display()
{
  int i;
  for(i=front1;i<=rear1;i++)
  {
    cout<<queue1[i]<<"\n";
  }
}
int main()
{
  int ch;
  cout<<"\n 1.Push \n 2.Pop \n 3.Display \n 4.Exit";
  while(1)
  {
    cout<<"\n Enter your choice";
    cin>>ch;
    switch(ch)
    {
      case 1:push();break;
      case 2: pop();break;
      case 3:display();break;
      case 4:exit(0);

    }
  }
  return 0;
}

Output:

 1.Push
 2.Pop
 3.Display
 4.Exit
 Enter your choice1
Enter element to be insert: 50

 Enter your choice1
Enter element to be insert: 40

 Enter your choice1
Enter element to be insert: 30

 Enter your choice1
Enter element to be insert: 20

 Enter your choice1
Enter element to be insert: 10

 Enter your choice3
50 40 30 20 10
Enter your choice2
10
 Enter your choice2
20
 Enter your choice2
30
 Enter your choice2
40
 Enter your choice2
50
 Enter your choice2
0
 Enter your choice3
0

You may also read:

Leave a Reply

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