Wednesday, November 4, 2020

Queue Using Stack | Code | C++

#include<iostream>

#include<stack>

using namespace std;

stack<int>s1;

stack<int>s2;



void push(int element){

s1.push(element);

}


int pop(){

    if(!s2.empty()){

        int r = s2.top();

        s2.pop();

        return r;

    }else{

        while(!s1.empty()){

            int t = s1.top();

            s1.pop();

            s2.push(t);

        }


        int r = s2.top();

        s2.pop();

        return r;

    }

}


int main(){


// s1 and s2

 //push : 1 2 3 4

 //pop :  ->  1

 //push : 5    -> 2 3 4 5

 //pop :   -> 2


 push(1);

 push(2);

 push(3);

 push(4);

 cout<<pop();

 push(5);

 cout<<'\n'<<pop();



return 0;}


NOTE : Write code for queue properties and even do check for empty before popping the element from the queue ...






No comments:

Post a Comment