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.
publicclassSolution{privatestaticStack<Long>stack1=newStack<>();privatestaticStack<Long>stack2=newStack<>();staticvoidenqueue(Longitem){stack1.push(item);}staticLongdequeue(){if(stack2.isEmpty()){while(!stack1.isEmpty()){stack2.push(stack1.pop());}}if(stack2.isEmpty()){returnnull;}returnstack2.pop();}staticLongpeek(){if(stack2.isEmpty()){while(!stack1.isEmpty()){stack2.push(stack1.pop());}}if(stack2.isEmpty()){returnnull;}returnstack2.peek();}publicstaticvoidmain(String[]args){/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */Scannerscanner=newScanner(System.in);longnumberOfQueries=Long.parseLong(scanner.nextLine());for(inti=1;i<=numberOfQueries;i++){String[]line=scanner.nextLine().split(" ");Stringcommand=line[0];switch(command){case"1":enqueue(Long.parseLong(line[1]));break;case"2":dequeue();break;case"3":System.out.println(peek());break;default:System.err.println("Bad command input!");}}scanner.close();}}
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: