We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
Approach : Here I'm using two stacks s1(as an supplementary stack) and s2 (acts as the main queue) , the top element of s2 will act as the Front element of the queue.
*I've written comments to help you understand the execution of queries, hope it help ;) *
First include the Stack Library using : #include <stack>
intmain(){/* Enter your code here. Read input from STDIN. Print output to STDOUT */stack<int>s1,s2;intquery_num;//no. of queriescin>>query_num;intquery,data;for(inti=0;i<query_num;i++){cin>>query;//1-Enqueueif(query==1){cin>>data;s1.push(data);}//2-Dequeueif(query==2){//if s2 is not empty --> pop the top element -- first element of our queueif(!s2.empty()){s2.pop();}//if s2 is empty --> then rev the s1 stack to s2--> then pop the top elemelse{while(!s1.empty()){s2.push(s1.top());s1.pop();}s2.pop();}}//3-Print the front element of queueif(query==3){//s2 is not empty --> print the top elem (front elem of queue)if(!s2.empty()){cout<<s2.top()<<endl;}//s2 is empty --> rev the stack s1 to s2 --> print top elem(front of queue)else{while(!s1.empty()){s2.push(s1.top());s1.pop();}cout<<s2.top()<<endl;}}}return0;}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Queue using Two Stacks
You are viewing a single comment's thread. Return to all comments →
Here's my code in C++
Approach : Here I'm using two stacks s1(as an supplementary stack) and s2 (acts as the main queue) , the top element of s2 will act as the Front element of the queue. *I've written comments to help you understand the execution of queries, hope it help ;) *
First include the Stack Library using :
#include <stack>