Queue using Two Stacks

  • + 0 comments

    Java and O(1)

    public static class QueueUsingTwoStacks<T> {
            private Stack<T> stack1; 
            private Stack<T> stack2; 
            
            public QueueUsingTwoStacks() {
                stack1 = new Stack<>();
                stack2 = new Stack<>();
            }
            
            public void enqueue(T element) {
                stack1.push(element);
            }
            
            public T dequeue() {
                if (stack2.isEmpty()) {
                    while (!stack1.isEmpty()) {
                        stack2.push(stack1.pop());
                    }
                }
                return stack2.pop();
            }
            
            public T peek() {
                if (stack2.isEmpty()) {
                    while (!stack1.isEmpty()) {
                        stack2.push(stack1.pop());
                    }
                }
                return stack2.peek();
            }
        }
    
        public static void main(String[] args) {
            Scanner scanner = new Scanner(System.in);
            int q = scanner.nextInt();
            QueueUsingTwoStacks<Integer> queue = new QueueUsingTwoStacks<>();
            
            for (int i = 0; i < q; i++) {
                int type = scanner.nextInt();
                if (type == 1) {
                    int x = scanner.nextInt();
                    queue.enqueue(x);
                } else if (type == 2) {
                    queue.dequeue();
                } else if (type == 3) {
                    System.out.println(queue.peek());
                }
            }
            scanner.close();
        }