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:
* take 2 stacks one for enque and another for deque.
* if operation is enqueue simply push to first stack
* if operation is dequeue - check if there are elements in 2nd stack if not copy all elements from 1st stack and pop the top. Otherwise simply pop 2nd stack top
* if operation is front - follow above step instead of popping print the top.
Gist is: stack 2 will have a top element to pop or print. We only copy stack 1 elements into stack 2 when it is empty.
intmain(){/* Enter your code here. Read input from STDIN. Print output to STDOUT */stack<int>st1;// for enqueuestack<int>st2;// for dequeueintnum_of_queries=0;cin>>num_of_queries;for(inti=0;i<num_of_queries;i++){intop;cin>>op;if(op==1){intdata;cin>>data;st1.push(data);continue;}if(op==2){if(!st2.empty()){st2.pop();}else{while(!st1.empty()){st2.push(st1.top());st1.pop();}st2.pop();}continue;}if(op==3){if(!st2.empty()){cout<<st2.top()<<endl;}else{while(!st1.empty()){st2.push(st1.top());st1.pop();}cout<<st2.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 →
Approach: * take 2 stacks one for enque and another for deque. * if operation is enqueue simply push to first stack * if operation is dequeue - check if there are elements in 2nd stack if not copy all elements from 1st stack and pop the top. Otherwise simply pop 2nd stack top * if operation is front - follow above step instead of popping print the top.
Gist is: stack 2 will have a top element to pop or print. We only copy stack 1 elements into stack 2 when it is empty.