LeetCode 232번 Implement Queue using Stacks JavaScript

찌니월드·5일 전
0

항해 99클럽 TIL

목록 보기
4/7

문제

두 개의 스택을 사용하여 FIFO(선입선출) 큐를 구현하는 문제이다.
즉, 큐의 메서드인 push, pop, peek, empty를 스택의 표준 연산만 사용하여 구현하면 된다.

문제 출처

232. Implement Queue using Stacks

나의 풀이

var MyQueue = function() {
    this.inStack = [];
    this.outStack = [];
};

/** 
 * @param {number} x
 * @return {void}
 */
MyQueue.prototype.push = function(x) {
    this.inStack.push(x);
};

/**
 * @return {number}
 */
MyQueue.prototype.pop = function() {
    if (this.outStack.length === 0) {
        while (this.inStack.length) {
            this.outStack.push(this.inStack.pop());
        }
    }
    return this.outStack.pop();
};

/**
 * @return {number}
 */
MyQueue.prototype.peek = function() {
    if (this.outStack.length === 0) {
        while (this.inStack.length) {
            this.outStack.push(this.inStack.pop());
        }
    }
    return this.outStack[this.outStack.length - 1];
};

/**
 * @return {boolean}
 */
MyQueue.prototype.empty = function() {
    return !this.inStack.length && !this.outStack.length;
};

/** 
 * Your MyQueue object will be instantiated and called as such:
 * var obj = new MyQueue()
 * obj.push(x)
 * var param_2 = obj.pop()
 * var param_3 = obj.peek()
 * var param_4 = obj.empty()
 */
profile
Front-End Developer

0개의 댓글

관련 채용 정보