[Algorithm] 42 week(11.14 ~ 11.20) 2/3

Dev_min·2022년 11월 15일
0

algorithm

목록 보기
136/157

232. Implement Queue using Stacks

var MyQueue = function() {
    this.input = [];
    this.output = [];
};

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

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

/**
 * @return {number}
 */
MyQueue.prototype.peek = function() {
    if(this.output.length) return this.output[this.output.length - 1];
        
    return this.input[0];
};

/**
 * @return {boolean}
 */
MyQueue.prototype.empty = function() {
    return this.input.length === 0 && this.output.length === 0;
};

/** 
 * 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
TIL record

0개의 댓글