算法打卡第十天 队列与栈1 232,225

40 阅读1分钟

232. 用栈实现队列

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

/** 
 * @param {number} x
 * @return {void}
 */
MyQueue.prototype.push = function(x) {
    this.queue.push(x);
};

/**
 * @return {number}
 */
MyQueue.prototype.pop = function() {
    let res = this.queue[0];
    this.queue.splice(0,1)
   return res;
};

/**
 * @return {number}
 */
MyQueue.prototype.peek = function() {
    return this.queue[0];
};

/**
 * @return {boolean}
 */
MyQueue.prototype.empty = function() {
    // 如果队列中存在
    if (this.queue.length === 0) {
        return true;
    }
    for (let i = 0; i < this.queue; i++) {

        if (this.queue[i] == '') {
            return true;
        } 
    }
    return false;
};

225. 用队列实现栈

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

/** 
 * @param {number} x
 * @return {void}
 */
MyStack.prototype.push = function(x) {
    this.stack.push(x);
};

/**
 * @return {number}
 */
MyStack.prototype.pop = function() {
    return this.stack.pop();
};

/**
 * @return {number}
 */
MyStack.prototype.top = function() {
    return this.stack[this.stack.length - 1];
};

/**
 * @return {boolean}
 */
MyStack.prototype.empty = function() {
    if (this.stack.length == 0) {
        return true;
    }
    for (let i = 0; i < this.stack.length; i++) {
        if (this.stack == '') {
            return true;
        }
    }
    return false;
};