Skip to content

232. 用栈实现队列【easy】 #34

Description

@devinxiang

描述

leetcode:https://leetcode-cn.com/problems/implement-queue-using-stacks/
image

分析:同用队列模拟栈一样,采用两个stack 和 _stack;栈先进后出;

  1. push:往 stack 中新增
  2. pop:删除栈顶的元素,需要把 stack 一个一个放进 _stack,这时候先进的就在_stack 的栈顶了,直接 pop 掉即可;当 _stack 为空,通过 while 把 stack 的数组全部倒腾过来;
  3. peek:获取栈顶元素,或者 _stack 顶部元素,如果没有则把stack 倒腾过来在获取;
  4. empty:判断 stack 和 _stack 长度都为0
/**
 * Initialize your data structure here.
 */
var MyQueue = function() {
  this.stack = [];
  this._stack = [];
};

/**
 * Push element x to the back of queue. 
 * @param {number} x
 * @return {void}
 */
MyQueue.prototype.push = function(x) {
  this.stack.push(x)
};

/**
 * Removes the element from in front of queue and returns that element.
 * @return {number}
 * 删除栈顶的元素的时,队列先进先出
 * 1. 当_stack 里面没有值的时候,把 stack 里面的倒腾过来,然后 pop _stack栈顶的元素
 * 2. 当_stack 里面有值的时候,直接 pop _stack 栈顶的元素;
 */
MyQueue.prototype.pop = function() {
  if (this._stack.length > 0) {
    return this._stack.pop()
  } else {
    while(this.stack.length > 0) {
      this._stack.push(this.stack.pop());
    }

    return this._stack.pop();
  }
};

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

    return this._stack[this._stack.length - 1];
  }
};

/**
 * Returns whether the queue is empty.
 * @return {boolean}
 */
MyQueue.prototype.empty = function() {
  return this.stack.length === 0 && this._stack.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()
 */

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions