(72). 24.4.2. Stack Using Queue. - anishsingh90/Data_Structure_And_Algorithm_In_Cpp_github.io GitHub Wiki

//Making Pop method Costly

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

class Stack{ int N; queue q1; queue q2;

public:
	Stack(){
		N = 0;
	}
	
	//pop operation
	void pop(){
		if(q1.empty()){
			return;
		}
		while(q1.size() != 1){
			q2.push(q1.front());
			q1.pop();
		}
		q1.pop();
		N--;
		
		queue<int> temp = q1;
		q1 = q2;
		q2 = temp;
	}
	
	
	//push operation
	void push(int val){
		q1.push(val);
		N++;
	}
	
	
	
	//top operation
	int top(){
		if(q1.empty()){
			return -1;
		}
		else{
			while(q1.size() != 1){
				q2.push(q1.front());
				q1.pop();
			}
			int ans = q1.front();
			q2.push(ans);
			
			queue<int> temp = q1;
			q1 = q2;
			q2 = temp;
			
			return ans;
		}
	}
	
	
	//size operation
	int size(){
		return N;
	}	

};

int main(){ Stack st; st.push(1); st.push(2); st.push(3); st.push(4);

cout << st.top() << endl; //print 4
st.pop(); //remove 4 
	
cout << st.top() << endl;  //print 3
cout << st.size() << endl; //print 3(size)
	
return 0;

}

/* OUTPUT: 4 3 3 */

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