Isaac Emmanuel
15 Jun 2024•EasyC++ / Python / TypeScript

Implement Queue using Stacks

C++, Python and TypeScript solutions for Implement Queue using Stacks.

The Implement Queue using Stacks solutions are below.

Solution files

Python•implement-queue-using-stacks/synced-solution.py
class MyQueue:
    def __init__(self):
        self.stack_in = []
        self.stack_out = []

    def push(self, x: int) -> None:
        self.stack_in.append(x)

    def pop(self) -> int:
        self.peek()
        return self.stack_out.pop()

    def peek(self) -> int:
        if not self.stack_out:
            while self.stack_in:
                self.stack_out.append(self.stack_in.pop())
        return self.stack_out[-1]

    def empty(self) -> bool:
        return len(self.stack_in) == 0 and len(self.stack_out) == 0
C++•implement-queue-using-stacks/synced-solution.cpp
class MyQueue {
private:
    stack<int> stackIn;
    stack<int> stackOut;
public:
    MyQueue() {}

    void push(int x) {
        stackIn.push(x);
    }

    int pop() {
        peek();
        int top = stackOut.top();
        stackOut.pop();
        return top;
    }

    int peek() {
        if (stackOut.empty()) {
            while (!stackIn.empty()) {
                stackOut.push(stackIn.top());
                stackIn.pop();
            }
        }
        return stackOut.top();
    }

    bool empty() {
        return stackIn.empty() && stackOut.empty();
    }
};
TypeScript•implement-queue-using-stacks/synced-solution.ts
class MyQueue {
    private stackIn: number[] = [];
    private stackOut: number[] = [];

    push(x: number): void {
        this.stackIn.push(x);
    }

    pop(): number {
        this.peek();
        return this.stackOut.pop()!;
    }

    peek(): number {
        if (this.stackOut.length === 0) {
            while (this.stackIn.length > 0) {
                this.stackOut.push(this.stackIn.pop()!);
            }
        }
        return this.stackOut[this.stackOut.length - 1];
    }

    empty(): boolean {
        return this.stackIn.length === 0 && this.stackOut.length === 0;
    }
}