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.io.*;importjava.util.*;importjava.util.stream.IntStream;importjava.util.stream.Collectors;publicclassSolution{publicstaticclassQueue_uts{staticStack<Integer>inputs=newStack<>();staticStack<Integer>outputs=newStack<>();// enqueuepublicstaticvoidadd(Integeritem){inputs.push(item);}// dequeuepublicstaticvoidremove(){sychronize();Integerpopped=outputs.pop();}publicstaticIntegerprint(){sychronize();// Integer peek = outputs.peek();// System.out.println(peek);returnoutputs.peek();}privatestaticvoidsychronize(){if(outputs.isEmpty())while(!inputs.isEmpty())outputs.push(inputs.pop());}}publicstaticList<Integer>queueUsingTwoStacks(List<List<Integer>>queries){// Write your code hereList<Integer>result=newArrayList<>();Queue_utsqueue=newQueue_uts();for(List<Integer>operation:queries){intop=operation.get(0);switch(op){case1:intoperand=operation.get(1);queue.add(operand);break;case2:queue.remove();break;case3:// queue.print();result.add(queue.print());break;default:System.out.println(String.format("operation type %d not allowed",op));}}returnresult;}publicstaticvoidmain(String[]args)throwsIOException{/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */List<List<Integer>>queries=newArrayList<>();BufferedReaderbufferedReader=newBufferedReader(newInputStreamReader(System.in));BufferedWriterbufferedWriter=newBufferedWriter(newFileWriter(System.getenv("OUTPUT_PATH")));intq=Integer.parseInt(bufferedReader.readLine().trim());IntStream.range(0,q).forEach(tItr->{try{Stringline=bufferedReader.readLine().trim();Integernum=null;intquery=-1;if(line.contains(" ")){query=Integer.valueOf(line.split(" ")[0]);num=Integer.valueOf(line.split(" ")[1]);}else{query=Integer.valueOf(line);}queries.add(newArrayList<>(Arrays.asList(query,num)));}catch(IOExceptionex){thrownewRuntimeException(ex);}});List<Integer>result=queueUsingTwoStacks(queries);// queueUsingTwoStacks(queries);bufferedWriter.write(result.stream().map(n->n.toString()+"\n").collect(Collectors.joining("")));bufferedReader.close();bufferedWriter.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 →
this is full answer