C++ program to implement queue using stacks.

So our queue will be having following below functions:

my_push(n) This function should insert the element ā€œnā€ at the end of the queue
my_pop() This function should remove the element from the front of the queue
my_peek() This function will return the front element
isEmpty() This function will check if the queue is empty or not.

We solve this problem by taking 2 stack variables.
In the input stack variable, we insert the values.
In the output stack variable, we do the pop and peek operations.

When we are doing a pop or peek operations, we move the elements from input stack to output stack.

Check the below code for more details.

Solution in C++

#include<iostream>
#include<stack>

using namespace std;

class MyQueue
{
	stack<int> input_stack;
	stack<int> output_stack;
public:
	void my_push(int x) 
	{
		input_stack.push(x);
	}

	void my_pop(void) 
	{
		my_peek();
		output_stack.pop();
	}

	int my_peek(void) 
	{
		// check if the output stack is empty,
		// if empty move the elements from input_stack to output_stack.
		if (output_stack.empty())
		{
			while (input_stack.size())
			{
				output_stack.push(input_stack.top()), input_stack.pop();
			}
		}
			return output_stack.top();
	}

	bool isEmpty(void) 
	{
		return input_stack.empty() && output_stack.empty();
	}

};

int main()
{
	MyQueue q;
	q.my_push(10);
	q.my_push(20);
	q.my_push(30);
	q.my_push(40);
	q.my_push(50);
	q.my_push(60);

	cout<<" using my_peek function = " << q.my_peek()<<endl;
	q.my_pop();
	cout<<" using my_peek function after my_pop for 1 time = " << q.my_peek()<<endl;


	return 0;
}

Output:

using my_peek function = 10
using my_peek function after my_pop for 1 time = 20

Write a Comment

Leave a Comment

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