Implement Queue using Stacks - LeetCode
Can you solve this real interview question? Implement Queue using Stacks - Implement a first in first out (FIFO) queue using only two stacks. The implemented queue should support all the functions of a normal queue (push, peek, pop, and empty). Implement t
leetcode.com
< 문제 간단설명 >
queue의 메소드인 push, peek, pop, empty를 두 개의 stack을 이용해서 구현한다.
var MyQueue = function () {
  this.stack1 = [];
  this.stack2 = [];
};
/**
 * @param {number} x
 * @return {void}
 */
MyQueue.prototype.push = function (x) {
  this.stack1.push(x);
};
/**
 * @return {number}
 */
MyQueue.prototype.pop = function () {
  if (this.stack2.length === 0) {
    while (this.stack1.length) {
      this.stack2.push(this.stack1.pop());
    }
  }
  return this.stack2.pop();
};
/**
 * @return {number}
 */
MyQueue.prototype.peek = function () {
  if (this.stack2.length === 0) {
    while (this.stack1.length) {
      this.stack2.push(this.stack1.pop());
    }
  }
  return this.stack2.at(-1);
};
/**
 * @return {boolean}
 */
MyQueue.prototype.empty = function () {
  return !this.stack1.length && !this.stack2.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()
 */'PS > LeetCode' 카테고리의 다른 글
| LeetCode / Array / 228번 / Summary Ranges / JS (0) | 2023.06.17 | 
|---|---|
| LeetCode / Design / 155번 / Min Stack / JS (0) | 2023.05.14 | 
| LeetCode / Tree / 199번 / Binary Tree Right Side View / JS (0) | 2023.05.14 | 
| LeetCode / Tree / 101번 / Symmetric Tree / JS (1) | 2023.05.14 |