Problem in implementation of queue

i have implemented queue using two stacks but my code is not working

#include <bits/stdc++.h>

using namespace std;

class Queue{

stack s1;
stack s2;
public:
void push(int element){
s1.push(element);
}
void pop() {
if(s1.empty()){
return;
}
while(s1.size()>1) {
int ele = s1.top();
s1.pop();
s2.push(ele);

      }
      s1.pop();
      swap(s1,s2);
   }

   int front1() {
             if(s1.empty()){
        return 0;
      }
      while(s1.size()>1) {
        s2.push(s1.top());
        s1.pop();
      }
      int element = s1.top();
      s1.pop();
      s2.push(element);
      swap(s1,s2);
     return element;


   }

};

int main() {

   Queue q;
    //q.push(1);
    q.push(2);
    q.push(3);

   cout<<q.front1();
   q.pop();
   cout<<q.front1();

   return 0;

}

Hi @Abhay_jain

Instead of swap(s1,s2) you need to put all elements in s2 back in s1. As while being transferred from s1 to s2 , all elements got reversed. Hence to get back original sequence reverse all elements in s2.

Corrected Code for Reference : https://ide.codingblocks.com/s/195480
If your query is resolved, mark this doubt as resolved.

Hope it Helps.

I didn’t get your point can you elaborate why I need to again push as a stack in S1 why swap didn’t work because If I push again then order again got changed which will not solve my problem please explain

I didn’t get your point can you elaborate why I need to again push as a stack in S1 why swap didn’t work because If I push again then order again got changed which will not solve my problem please explain

While putting elements in s2 you already reversed the order of original stack, hence to get back original stack after removing an element , you need to put back s2 in s1 by reversing it.

@Abhay_jain

If your query is resolved, then please mark it as resolved.

Thanks

@Abhay_jain
Please mark your doubt as solved.

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.