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.
importjava.util.Scanner;importjava.util.Stack;publicclassSolution{publicstaticvoidmain(String[]args){MyQueue<Integer>queue=newMyQueue<Integer>();Scannerscan=newScanner(System.in);intn=scan.nextInt();for(inti=0;i<n;i++){intoperation=scan.nextInt();if(operation==1){// enqueuequeue.enqueue(scan.nextInt());}elseif(operation==2){// dequeuequeue.dequeue();}elseif(operation==3){// print/peekSystem.out.println(queue.peek());}}scan.close();}publicstaticclassMyQueue<Integer>{privateStack<Integer>stack1=newStack<>();privateStack<Integer>stack2=newStack<>();publicvoidenqueue(Integernum){stack1.push(num);}publicIntegerdequeue(){if(size()==0){returnnull;}if(stack2.isEmpty()){shiftStacks();}returnstack2.pop();}publicIntegerpeek(){if(size()==0){returnnull;}if(stack2.isEmpty()){shiftStacks();}returnstack2.peek();}/* Only shifts stacks if necessary */privatevoidshiftStacks(){if(stack2.isEmpty()){// shifting items while stack2 contains items would mess up our queue's orderingwhile(!stack1.isEmpty()){stack2.push(stack1.pop());}}}publicintsize(){returnstack1.size()+stack2.size();}}}
Let me know if you have any questions.
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 →
Java solution - passes 100% of test cases
From my HackerRank Java solutions.
Let me know if you have any questions.