CodingTest/LeetCode

[LeetCode] 225. Implement Stack using Queues, Easy

뜸부깅 2025. 4. 3. 13:33
반응형

1. 문제

  • 2개의 큐를 사용해서 stack을 구현하라

2.해결

class MyStack {
    inputQueue: number[];
    outputQueue: number[];

    constructor() {
        this.inputQueue = new Array();
        this.outputQueue = new Array();
    }

    push(x: number): void {
        
        while(this.outputQueue.length > 0) {
            this.inputQueue.push(this.outputQueue.shift())
        }

        this.inputQueue.push(x);

        while(this.inputQueue.length > 0) {
            this.outputQueue.push(this.inputQueue.shift())
        }
        
    }

    pop(): number {
        return this.outputQueue.pop()
    }

    top(): number {
        return this.outputQueue[this.outputQueue.length - 1];
    }

    empty(): boolean {
        return this.outputQueue.length === 0
    }
}

/**
 * Your MyStack object will be instantiated and called as such:
 * var obj = new MyStack()
 * obj.push(x)
 * var param_2 = obj.pop()
 * var param_3 = obj.top()
 * var param_4 = obj.empty()
 */
  • 큐의 방향이 반대로 되게 2개를 위치시켰다는 생각으로 구현해봤다.