dailycodebase

2 month data structures and algorithmic scripting challenge starting from 20th December 2018 - Coding is Fun! πŸ’―πŸ’― Do it everyday!! Also, Do give us a ⭐ if you liked the repository

View on GitHub

cover

Day 44 - Queue from Stacks

Implement the Queue data structure using Stacks

Hint

Use 2 stacks

Don’t forget to restore the state of first stack after the dequeue and peek operations

Solution

JavaScript Implementation

Solution

class Queue {
    constructor(size) {
        this.first = new Stack();
        this.second = new Stack();
    }

    enqueue(element) {
        this.first.push(element);
    }

    dequeue() {
        // Empty first stack to second
        while (this.first.peek()) {
            this.second.push(this.first.pop());
        }

        const element = this.second.pop();

        // Restore first stack
        while (this.second.peek()) {
            this.first.push(this.second.pop());
        }

        return element;
    }

    peek() {
        while (this.first.peek()) {
            this.second.push(this.first.pop());
        }

        const element = this.second.peek();

        while (this.second.peek()) {
            this.first.push(this.second.pop());
        }

        return element;
    }
}

Click Here for complete solution