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.
Java8 Straightforward and best time-complexity solution:
importjava.io.*;importjava.util.*;publicclassSolution{privatestaticScannerscanner=newScanner(System.in);privatestaticStack<Integer>s1=newStack<Integer>();privatestaticStack<Integer>s2=newStack<Integer>();privatestaticvoidenqueue(intvalue){s1.push(value);}privatestaticvoiddequeue(){if(s2.isEmpty()==true){while(s1.isEmpty()==false){inttoS2=s1.pop();s2.push(toS2);}}intreturnValue=s2.pop();}privatestaticvoidpeak(){if(s2.isEmpty()==true){while(s1.isEmpty()==false){inttoS2=s1.pop();s2.push(toS2);}}System.out.println(s2.peek());}publicstaticvoidmain(String[]args){/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */inttotal=scanner.nextInt();for(inti=0;i<total;i++){inttype=scanner.nextInt();if(type==1){enqueue(scanner.nextInt());}elseif(type==2){dequeue();}elseif(type==3){peak();}}}}
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 →
Java8 Straightforward and best time-complexity solution: