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.
public class Solution {
private Stack stackEnqueue = new Stack<>();
private Stack stackDequeue = new Stack<>();
// Enqueue
public void enqueue(int n){
stackEnqueue.push(n);
}
// Dequeue
public void dequeue(){
reverseStack();
if(!stackDequeue.isEmpty()){
stackDequeue.pop();
}
}
//Reverse
private void reverseStack(){
if(stackDequeue.isEmpty()){
while(!stackEnqueue.isEmpty()){
stackDequeue.push(stackEnqueue.pop());
}
}
}
//Print front element
public void printFrontElement(){
reverseStack();
if(!stackDequeue.isEmpty()){
System.out.println(stackDequeue.peek());
}
}
public static void main(String[] args) {
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
Scanner scanner = new Scanner((System.in));
Solution twoStackQueue = new Solution();
int count = scanner.nextInt();
for(int i = 0; i< count; i++){
int choice = scanner.nextInt();
switch (choice){
case 1:
int enqueueNumber = scanner.nextInt();
twoStackQueue.enqueue(enqueueNumber);
break;
case 2:
twoStackQueue.dequeue();
break;
case 3:
twoStackQueue.printFrontElement();
break;
}
}
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 solution
public class Solution { private Stack stackEnqueue = new Stack<>(); private Stack stackDequeue = new Stack<>();
}