fork download
  1. #include <iostream>
  2. #include <stack>
  3. using namespace std;
  4.  
  5. template<typename T>
  6. class Queue2Stack
  7. {
  8. stack<T> in, out;
  9. public:
  10. void push( const T& what )
  11. {
  12. while( !out.empty() )
  13. {
  14. in.push( out.top() );
  15. out.pop();
  16. }
  17. in.push( what );
  18. }
  19.  
  20. T pop()
  21. {
  22. while( !in.empty() )
  23. {
  24. out.push( in.top() );
  25. in.pop();
  26. }
  27. T result = out.top();
  28. out.pop();
  29. return result;
  30. }
  31. };
  32.  
  33. int main() {
  34. Queue2Stack<int> st;
  35. cout << "push 1, 2" << endl;
  36. st.push(1);
  37. st.push(2);
  38. cout << "pop " << st.pop() << endl;
  39. cout << "push 3, 4" << endl;
  40. st.push(3);
  41. st.push(4);
  42. cout << "pop " << st.pop() << ", ";
  43. cout << st.pop() << ", ";
  44. cout << st.pop() << endl;
  45.  
  46. return 0;
  47. }
Success #stdin #stdout 0s 3432KB
stdin
Standard input is empty
stdout
push 1, 2
pop 1
push 3, 4
pop 2, 3, 4