zoukankan      html  css  js  c++  java
  • leetcode每日一题(2020-06-30):剑指 Offer 09. 用两个栈实现队列

    题目描述:
    用两个栈实现一个队列。队列的声明如下,请实现它的两个函数 appendTail 和 deleteHead ,分别完成在队列尾部插入整数和在队列头部删除整数的功能。(若队列中没有元素,deleteHead 操作返回 -1 )

    今日学习:
    1.没学啥好像。。。

    题解:

    var CQueue = function() {
        // this.queue = []
        this.stack1 = []
        this.stack2 = []
    };
    
    /** 
     * @param {number} value
     * @return {void}
     */
    CQueue.prototype.appendTail = function(value) {
        // this.queue.push(value)
        this.stack1.push(value)
    };
    
    /**
     * @return {number}
     */
    CQueue.prototype.deleteHead = function() {
        // if(this.queue.length != 0) {
        //     return this.queue.shift()
        // }else {
        //     return -1
        // }
    
        // if(this.stack2.length == 0) {
        //     while(this.stack1.length) {
        //         this.stack2.push(this.stack1.pop());
        //     }
        // }
        // return this.stack2.pop() || -1;
    
        //如果第二个栈中有元素,直接pop()
        if(this.stack2.length){
            return this.stack2.pop()
        }
        //如果第一个栈为空,则直接返回--1
        if(!this.stack1.length) return -1
        //将第一个栈中的元素倒置进第二个栈中
        while(this.stack1.length){
            this.stack2.push(this.stack1.pop())
        }
        return this.stack2.pop()
    };
    
    /**
     * Your CQueue object will be instantiated and called as such:
     * var obj = new CQueue()
     * obj.appendTail(value)
     * var param_2 = obj.deleteHead()
     */
    
  • 相关阅读:
    2.3 节的练习
    2.2 节的练习--Compiler principles, technologys, &tools
    web测试点整理(二) -- 输入框
    web测试点整理 -- 注册/登录
    产品测试的思路
    C语言学习--静态链接库和动态链接库
    C语言学习(四)--操作符
    C语言学习(三)--语句
    C语言学习(二)--数据类型
    C语言学习(一)--基本概念
  • 原文地址:https://www.cnblogs.com/autumn-starrysky/p/13211873.html
Copyright © 2011-2022 走看看