fork download
  1. #include <iostream>
  2. #include <queue>
  3. using namespace std;
  4.  
  5. class Stack {
  6. private:
  7. queue<int> q1, q2;
  8.  
  9. public:
  10. void push(int x) {
  11. q2.push(x);
  12. while (!q1.empty()) {
  13. q2.push(q1.front());
  14. q1.pop();
  15. }
  16. swap(q1, q2);
  17. }
  18.  
  19. int pop() {
  20. if (!q1.empty()) {
  21. int element = q1.front();
  22. q1.pop();
  23. return element;
  24. }
  25. else{
  26. cout<<"Stack Underflow";
  27. return -1;
  28. }
  29. }
  30. };
  31.  
  32. int main() {
  33. Stack myStack;
  34.  
  35. cout<<"Pushing 1 then 2 then 3"<<endl;
  36. myStack.push(1);
  37. myStack.push(2);
  38. myStack.push(3);
  39. cout<<"Popping...."<<endl;
  40. int element = myStack.pop();
  41. cout<<"Popped element: "<<element<<endl;
  42.  
  43. return 0;
  44. }
Success #stdin #stdout 0.01s 5280KB
stdin
Standard input is empty
stdout
Pushing 1 then 2 then 3
Popping....
Popped element: 3