# 用栈实现队列 (opens new window)
- 难度:Easy
- 标签:
# 刷题思路
- [x] 用数组实现队列(简单但不可取)
- [x] 用两个栈实现队列
# 方法 1 用数组实现队列
# 方法 2 用两个栈实现队列
/**
* Initialize your data structure here.
*/
var MyQueue = function() {
this.mStack = []
this.stack = []
};
/**
* Push element x to the back of queue.
* @param {number} x
* @return {void}
*/
MyQueue.prototype.push = function(x) {
while (this.stack.length !== 0) this.mStack.push(this.stack.pop())
this.mStack.push(x)
while (this.mStack.length !== 0) this.stack.push(this.mStack.pop())
};
/**
* Removes the element from in front of queue and returns that element.
* @return {number}
*/
MyQueue.prototype.pop = function() {
return this.stack.pop()
};
/**
* Get the front element.
* @return {number}
*/
MyQueue.prototype.peek = function() {
const ele = this.stack.pop()
this.stack.push(ele)
return ele
};
/**
* Returns whether the queue is empty.
* @return {boolean}
*/
MyQueue.prototype.empty = function() {
return this.peek() === undefined
};
JS刷题记录 Leetcode-js (opens new window) 每周都会更新刷题心得或者题解, 你的点赞或 star 都将助力我产出更好内容~