Queue using Two Stacks

Sort by

recency

|

24 Discussions

|

  • + 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();
        }
    
  • + 0 comments

    JS

    Barely able to pass without the timeout error after trying multiple times:

    function processData(input) {
        let s1 = [], s2 = []
        let inputs = input.split('\n')
        for (let i = 1; i < inputs.length; i++) {
            let arr = inputs[i].split(' ')
            switch (arr[0]) {
                case '1': {
                    s1.push(arr[1])
                    break
                }
                case '2': {
                    while (s1.length > 0) s2.push(s1.pop())
                    s2.pop()
                    while (s2.length > 0) s1.push(s2.pop())
                    break
                }
                case '3': {
                    console.log(s1[0])
                    break
                }
            }
        }
    }
    
  • + 0 comments

    Java8 Straightforward and best time-complexity solution:

    import java.io.*;
    import java.util.*;
    
    public class Solution {
        private static Scanner scanner = new Scanner(System.in);
        private static Stack<Integer> s1 = new Stack<Integer>();
        private static Stack<Integer> s2 = new Stack<Integer>();
        private static void enqueue(int value){
                s1.push(value);
            }
            
        private static void dequeue(){
                if (s2.isEmpty() == true){
                    while (s1.isEmpty() == false){
                        int toS2 = s1.pop();
                        s2.push(toS2);
                    }
                }
                int returnValue = s2.pop();
            }
            
        private static void peak(){
                if (s2.isEmpty() == true){
                    while (s1.isEmpty() == false){
                        int toS2 = s1.pop();
                        s2.push(toS2);
                    }
                }
                System.out.println(s2.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. */
            int total = scanner.nextInt();
            for (int i = 0; i < total; i++) {
                int type = scanner.nextInt();
                if (type == 1){
                    enqueue(scanner.nextInt());
                }
                else if (type == 2){
                    dequeue();
                }
                else if (type == 3){
                    peak();
                }
            }
            
            
            
            
        }
    }
    
  • + 1 comment

    C++20 -- My code keeps getting "Time Limit Exceeded" for many test cases and works for the rest. Could someone help me address that?

    struct Queue {
        stack<int> stack1, stack2; // we will use these two stacks; stack1 is where we will store and pop from, stack2 is used just as a transfer-device
     
        void Enqueue(int x) // to enqueue x at the end of the queue
        {
            while (!stack1.empty()) { // until stack1 is empty
                stack2.push(stack1.top()); // push element from top of stack1 into stack2
                stack1.pop(); // remove the top of stack1 to expose the next top
            }
     
            // Push x into s1, which is currently empty
            stack1.push(x);
     
            // Now take everything from stack2 and put it back in stack1
            while (!stack2.empty()) {
                stack1.push(stack2.top());
                stack2.pop();
            }
        }
        
        void Dequeue(){
            stack1.pop();
        }
     
        // Dequeue an item from the queue
        int Get_Front()
        {
            // Return top of s1
            int x = stack1.top(); // x is the top of stack1
            //stack1.pop(); // throw away top of stack1
            return x; // return the top of stack1
        }
        
    };
    
    int main(){
        Queue queue;
        int q;
        cin >> q;
        int query;
        for (int i = 0; i < q-1; i++){
            cin >> query;
            if (query == 1){
                int x;
                cin >> x;
                queue.Enqueue(x);
            }
            else if (query == 2) queue.Dequeue();
            else cout << queue.Get_Front() << endl;
        }
    
  • + 0 comments

    JS

    function processData(input) {
        const queue = {
            inbound: [],
            outbound: [],
            enqueue(data) {
                this.inbound.push(data);
            },
            dequeue() {
                if (this.outbound.length == 0) {
                    while (this.inbound.length > 0) {
                        this.outbound.push(this.inbound.pop());
                    }
                }
                return this.outbound.pop();
            },
            get() {
                return this.outbound.length ? this.outbound.at(-1) : this.inbound[0];
            }
        };
    
        input.split("\n").slice(1).forEach(query => {
            const type = query.at(0);
            if (type == "1") {
                queue.enqueue(query.split(" ")[1]);
            }
            else if (type == "2") {
                queue.dequeue();
            }
            else {
                console.log(queue.get());
            }
        });
    }