Advertisement
RaresDumitrica

Queue from Stack STL

Jan 17th, 2019
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.00 KB | None | 0 0
  1. #include <iostream>
  2. #include <stack>
  3.  
  4. using namespace std;
  5.  
  6. struct Queue
  7.     {
  8.     stack<int> s1, s2;
  9.  
  10.     void enQueue(int x)
  11.     {
  12.         // Move all elements from s1 to s2
  13.         while (!s1.empty())
  14.         {
  15.             s2.push(s1.top());
  16.             s1.pop();
  17.         }
  18.  
  19.         // Push item into s1
  20.         s1.push(x);
  21.  
  22.         // Push everything back to s1
  23.         while (!s2.empty())
  24.         {
  25.             s1.push(s2.top());
  26.             s2.pop();
  27.         }
  28.     }
  29.  
  30.     // Dequeue an item from the queue
  31.     int deQueue()
  32.     {
  33.         // if first stack is empty
  34.         if (s1.empty())
  35.         {
  36.             cout << "Q is Empty";
  37.             exit(0);
  38.         }
  39.  
  40.         // Return top of s1
  41.         int x = s1.top();
  42.         s1.pop();
  43.         return x;
  44.     }
  45. };
  46.  
  47. int main()
  48. {
  49.     Queue q;
  50.     q.enQueue(1);
  51.     q.enQueue(2);
  52.     q.enQueue(3);
  53.  
  54.     cout << q.deQueue() << '\n';
  55.     cout << q.deQueue() << '\n';
  56.     cout << q.deQueue() << '\n';
  57.  
  58.     return 0;
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement