(70). 24.3. Queue Using Stack - anishsingh90/Data_Structure_And_Algorithm_In_Cpp_github.io GitHub Wiki

//Queue using 2 Stack

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

class Myqueue{ stack s1; stack s2;

public:
	void push(int x){
		s1.push(x);
	}
	
	//pop operation
	int pop(){
		if(s1.empty() && s2.empty()){
			cout << "Queue is empty\n";
			return -1;
		}
		if(s2.empty()){
			while(!s1.empty()){
				s2.push(s1.top());
				s1.pop();
			}
		}
		int topval = s2.top();
		s2.pop();
		return topval;
	}
	
	//empty operation
	bool empty(){
		if(s1.empty() && s2.empty()){
			return true;
		}
		else{
			return false;
		}
	}

};

int main(){

Myqueue q;
q.push(1);
q.push(2);
q.push(3);
q.push(4);

cout << q.pop() << endl;
q.push(5); 

cout << q.pop() << endl; 
cout << q.pop() << endl; 
cout << q.pop() << endl; 
cout << q.pop() << endl;
cout << q.pop() << endl;
	
return 0;

}

/* OUTPUT: 1 2 3 4 5 Queue is empty -1 */

//Queue using 1 Stack By Recursion

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

class Myqueue{ stack s1;

public:
	void push(int x){
		s1.push(x);
	}
	
	//pop operation
	int pop(){
		if(s1.empty()){
			cout << "Queue is empty\n";
			return -1;
		}
		
		int x = s1.top();
		s1.pop();
		
		if(s1.empty()){
			return x;
		}
		
		int item = pop();
		s1.push(x);
		return item;
	}
	
	//empty operation
	bool empty(){
		if(s1.empty()){
			return true;
		}
		else{
			return false;
		}
	}

};

int main(){

Myqueue q;
q.push(1);
q.push(2);
q.push(3);
q.push(4);

cout << q.pop() << endl;
q.push(5); 

cout << q.pop() << endl; 
cout << q.pop() << endl; 
cout << q.pop() << endl; 
cout << q.pop() << endl;
cout << q.pop() << endl;
	
return 0;

}

/* OUTPUT: 1 2 3 4 5 Queue is empty -1 */

⚠️ **GitHub.com Fallback** ⚠️