15 Jun 2024C++ / Python / TypeScriptEasy

Implement Queue using Stacks

Collected C++, Python, TypeScript solutions for implement queue using stacks. Add a dedicated write-up later if you want deeper notes.

auto-generated entry for Implement Queue using Stacks. the solution files are available below.

solution files

  • C++ implement-queue-using-stacks/synced-solution.cpp
  • Python implement-queue-using-stacks/synced-solution.py
  • TypeScript implement-queue-using-stacks/synced-solution.ts

Solution files

Pythonimplement-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[-class="syntax-number">1]

    def empty(self) -> bool:
        return len(self.stack_in) == class="syntax-number">0 and len(self.stack_out) == class="syntax-number">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();
    }
};
TypeScriptimplement-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 === class="syntax-number">0) {
            while (this.stackIn.length > class="syntax-number">0) {
                this.stackOut.push(this.stackIn.pop()!);
            }
        }
        return this.stackOut[this.stackOut.length - class="syntax-number">1];
    }

    empty(): boolean {
        return this.stackIn.length === class="syntax-number">0 && this.stackOut.length === class="syntax-number">0;
    }
}