LeetCode-算法题系列 (十九) => 用栈实现队列

leetCode第232题

这道题的场景在实际需求中基本上不会遇见,但挺有意思的,值得我们去思考

解法

LeetCode-算法题系列 (十九) => 用栈实现队列_第1张图片

/**
 * Initialize your data structure here.
 */
var MyQueue = function() {
  this.aStack = [] //我们需要两个数组来帮助我们逆序一个堆栈
  this.bStack = []   
};

/**
 * Push element x to the back of queue. 
 * @param {number} x
 * @return {void}
 */
MyQueue.prototype.push = function(x) {
  this.aStack.push(x)
  
  // var lenA = this.aStack.length
  // this.aStack[lenA] = x
};

/**
 * Removes the element from in front of queue and returns that element.
 * @return {number}
 */
MyQueue.prototype.pop = function() {
  // a栈出栈押入b栈,则会形成和队列一样的顺序,最后返回b栈的末尾位,即a栈的首位
  if(this.bStack.length){
    return this.bStack.pop()
  }
  while(this.aStack.length){
    this.bStack.push(this.aStack.pop())
  }
  return this.bStack.pop()
};

/**
 * Get the front element.
 * @return {number}
 */
MyQueue.prototype.peek = function() {
  if(this.bStack.length){
    return this.bStack[this.bStack.length-1]
  }
  while(this.aStack.length){
    this.bStack.push(this.aStack.pop())
  }
  return this.bStack[this.bStack.length-1]
};

/**
 * Returns whether the queue is empty.
 * @return {boolean}
 */
MyQueue.prototype.empty = function() {
  while(this.aStack.length){
    this.bStack.push(this.aStack.pop())
  }
  return this.bStack.length <= 0

};

你可能感兴趣的:(堆栈算法,leetCode,用栈实现队列,js,前端算法,FE-daily-算法题,算法面试通关)