You are viewing a single comment's thread. Return to all comments →
import java.io.*; import java.util.*; import java.text.*; import java.math.*; import java.util.regex.*; public class Solution { public static class MyQueue<T> { Stack<T> stackNewestOnTop = new Stack<T>(); Stack<T> stackOldestOnTop = new Stack<T>(); public void enqueue(T value) { // Push onto newest stack stackNewestOnTop.push(value); } private void switchStack(){ if(stackOldestOnTop.empty()){ while(!stackNewestOnTop.empty()){ stackOldestOnTop.push(stackNewestOnTop.pop()); } } } public T peek() { switchStack(); return stackOldestOnTop.peek(); } public T dequeue() { switchStack(); return stackOldestOnTop.pop(); } } 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(); } }
Seems like cookies are disabled on this browser, please enable them to open this website
Validating Credit Card Numbers
You are viewing a single comment's thread. Return to all comments →