Skip to content

Instantly share code, notes, and snippets.

@feliperazeek
Created October 15, 2016 04:41
Show Gist options
  • Save feliperazeek/ac00a7da6e961c54cd12586f38c88e46 to your computer and use it in GitHub Desktop.
Save feliperazeek/ac00a7da6e961c54cd12586f38c88e46 to your computer and use it in GitHub Desktop.
HackerRank - Cracking the Code Interview - Queues: A Tale of Two Stacks (https://www.hackerrank.com/challenges/ctci-queue-using-two-stacks)
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
private static class MyQueue<T> {
private Stack<T> in = new Stack<T>();
private Stack<T> out = new Stack<T>();
public void enqueue(T item) {
in.push(item);
}
public T dequeue() {
if (out.isEmpty()) {
while (!in.empty()) {
out.push(in.pop());
}
}
return out.pop();
}
public T peek() {
if (out.isEmpty()) {
while (!in.empty()) {
out.push(in.pop());
}
}
return out.peek();
}
}
public static void main(String[] args) {
MyQueue<Integer> queue = new MyQueue<Integer>();
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
for (int i = 0; i < n; i++) {
int operation = scan.nextInt();
if (operation == 1) { // enqueue
queue.enqueue(scan.nextInt());
} else if (operation == 2) { // dequeue
queue.dequeue();
} else if (operation == 3) { // print/peek
System.out.println(queue.peek());
}
}
scan.close();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment