You are viewing a single comment's thread. Return to all comments →
java code:
import java.util.Scanner; import java.util.Stack; public class Main { public static void main(String[] args) { try (var scanner = new Scanner(System.in)) { var inputSize = scanner.nextInt(); final var queue = new MyQueue(); for (int i = 0; i < inputSize; i++) { var commandId = scanner.nextInt(); switch (commandId) { case 1 -> { var payload = scanner.nextInt(); queue.enqueue(payload); } case 2 -> queue.dequeue(); case 3 -> queue.print(); } } } } public static class MyQueue { final Stack<Integer> input = new Stack<>(); final Stack<Integer> reverseTail = new Stack<>(); public void enqueue(int value) { input.push(value); } public void dequeue() { if (reverseTail.isEmpty()) { transferFromHeadToReverseTail(); } if (reverseTail.isEmpty()) { return; } reverseTail.pop(); } private void transferFromHeadToReverseTail() { var size = input.size(); for (int i = 0; i < size; i++) { var obj = input.pop(); reverseTail.push(obj); } } public void print() { if (reverseTail.isEmpty()) { transferFromHeadToReverseTail(); } if (reverseTail.isEmpty()) { return; } System.out.println(reverseTail.peek()); } } }
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 code: