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.
Thanks to hackerrank4021 , Java solution is below.
importjava.io.*;importjava.util.*;/*a. For insert, insert into stack1.b. For deque, deque from stack2. If it is not empty transfer from 1 to 2 and deque from 2.c. For peek, show peek of stack2. If empty transfer from 1 to 2 and then peek from 2.*/publicclassSolution{publicstaticStack<Integer>sta1=newStack();publicstaticStack<Integer>sta2=newStack();publicstaticvoidmain(String[]args){/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */// only below is poss in stacks// sta1.removeLast();Scannersc=newScanner(System.in);intnoQ=sc.nextInt();while(noQ-->0){switch(sc.next()){case"1":insertQueue(sc.nextInt());// print queue top// printQueueHead();break;case"2":deQueue();break;case"3":printQueueHead();break;case"q":return;default:System.out.println("Invalid input!");break;}}}publicstaticvoidinsertQueue(intitem){sta1.add(item);}publicstaticvoidtransfer(){if(sta1.size()==0)return;do{sta2.push(sta1.pop());}while(sta1.size()>0);}publicstaticIntegerdeQueue(){if(sta2.size()==0){if(sta1.size()==0){returnnull;}transfer();}returnsta2.pop();}// sta1 s last element is the queue headpublicstaticvoidprintQueueHead(){if(sta2.size()==0){if(sta1.size()==0){return;}transfer();}System.out.println(sta2.peek());}}
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 →
Thanks to hackerrank4021 , Java solution is below.