Advertisement
vaibhav1906

Queue using stacks

Dec 17th, 2021
1,267
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.94 KB | None | 0 0
  1. class MyQueue {
  2. public:
  3.     stack <int> s1; //Primary Stack
  4.     stack <int> s2; //Secondary Stack    
  5.    
  6.     MyQueue() {
  7.        
  8.     }
  9.    
  10.     void push(int x) {
  11.         s1.push(x);
  12.     }
  13.    
  14.     int pop() {
  15.        while(s1.size()!=0){
  16.            s2.push(s1.top());
  17.            s1.pop();
  18.        }
  19.        int ans = s2.top();
  20.         s2.pop();
  21.        
  22.        while(s2.size()!=0){
  23.            s1.push(s2.top());
  24.            s2.pop();
  25.        }
  26.        
  27.         return ans;
  28.        
  29.     }
  30.    
  31.     int peek() {
  32.         while(s1.size()!=0){
  33.            s2.push(s1.top());
  34.            s1.pop();
  35.        }
  36.        int ans = s2.top();
  37.        
  38.        while(s2.size()!=0){
  39.            s1.push(s2.top());
  40.            s2.pop();
  41.        }
  42.        
  43.         return ans;
  44.     }
  45.    
  46.     bool empty() {
  47.        
  48.         if(s1.size()==0){
  49.             return true;
  50.         }
  51.        
  52.         return false;
  53.        
  54.        
  55.     }
  56. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement