[leetcode刷题]D10_栈与队列

用两个堆栈实现队列

题目链接
讲解链接
在这里插入图片描述

var MyQueue = function() {
    //写入栈
    this.stackIn = [];
    //弹出栈
    this.stackOut = [];
};

/** 
 * @param {number} x
 * @return {void}
 */
 //写入栈顶,与队列在尾部增强元素规则一样,直接push
MyQueue.prototype.push = function(x) {
    this.stackIn.push(x)

};

/**
 * @return {number}
 */
 //弹出操作,需要两次入栈出栈,一次入栈是LIFO,两次入栈就是FIFO
MyQueue.prototype.pop = function() {
    const size = this.stackOut.length;
    if(size) {
        return this.stackOut.pop();
    }
    while(this.stackIn.length) {
        this.stackOut.push(this.stackIn.pop());
    }
    return this.stackOut.pop();
};

/**
 * @return {number}
 */
 //返回队头元素,实际上就是弹出栈的栈顶
MyQueue.prototype.peek = function() {
    const result = this.pop();
    this.stackOut.push(result);
    return this.stackOut[this.stackOut.length - 1];
};

/**
 * @return {boolean}
 */
MyQueue.prototype.empty = function() {
return !this.stackIn.length && !this.stackOut.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()
 */
  • 队列是队头(front)出数据(pop),队尾(end)进数据(push),可对比日常生活中的排队。在计算机中常见的例子比如打印队列,就是先进先处理。
  • 堆栈是进栈和出栈全在一端操作,即栈顶。是一种先进后出的数据结构。主要应用包括在编译器和内存中保存变量、方法调用等,也被用于浏览器和其他应用的历史记录(返回按钮)。
  • 用堆栈实现队列,写入操作是一样的,直接push。但是pop和peek需要两个堆栈,首先将待写数据写入输入堆栈,此时如果直接出栈,那么是FILO。但是如果加一个弹出栈来接受写入栈弹出的元素,那么元素再从弹出栈进行pop操作的时候,相当于2次倒序,那么就符合队列从头部弹出数据的要求了(2*FILO = FIFO).

用单个队列实现堆栈

题目链接
讲解链接
在这里插入图片描述

var MyStack = function() {
this.queue = [];
};

/** 
 * @param {number} x
 * @return {void}
 */
 //写入规则一样,栈顶即队尾
MyStack.prototype.push = function(x) {
    this.queue.push(x);

};

/**
 * @return {number}
 */
 //弹出栈顶元素,就是队尾
MyStack.prototype.pop = function() {
    if(this.queue.length !== null) {
        let result  = this.queue[this.queue.length - 1];
        this.queue.pop();
        return result;
    }
    
};

/**
 * @return {number}
 */
 //返回队尾元素
MyStack.prototype.top = function() {
    return this.queue[this.queue.length - 1];
};

/**
 * @return {boolean}
 */
 //length为0即为空
MyStack.prototype.empty = function() {
    return !this.queue.length

};

/**
 * Your MyStack object will be instantiated and called as such:
 * var obj = new MyStack()
 * obj.push(x)
 * var param_2 = obj.pop()
 * var param_3 = obj.top()
 * var param_4 = obj.empty()
 */

心得体会

坚持就是胜利!耶!每一天都元气满满!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值