LeetCode《程序员面试金典》面试题 03.04. 化栈为队

LeetCode 面试题 03.04. 化栈为队

题目

在这里插入图片描述

解题

解题一

在这里插入图片描述

/**
 * Initialize your data structure here.
 */
var MyQueue = function() {
    this.inStack = [];
    this.outStack = [];
};

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

/**
 * Removes the element from in front of queue and returns that element.
 * @return {number}
 */
MyQueue.prototype.pop = function() {
    if (this.empty()) return -1;
    this.moveStack(this.inStack, this.outStack);
    const x = this.outStack.pop();
    this.moveStack(this.outStack, this.inStack);
    return x;
};

/**
 * Get the front element.
 * @return {number}
 */
MyQueue.prototype.peek = function() {
    if (this.empty()) return -1;
    this.moveStack(this.inStack, this.outStack);
    const x = this.outStack[this.outStack.length - 1];
    this.moveStack(this.outStack, this.inStack);
    return x;
};

/**
 * Returns whether the queue is empty.
 * @return {boolean}
 */
MyQueue.prototype.empty = function() {
    return this.inStack.length === 0;
};

MyQueue.prototype.moveStack = function(src, des) {
    while (src.length) {
        des.push(src.pop());
    }
};

解题二

在这里插入图片描述

/**
 * Initialize your data structure here.
 */
var MyQueue = function() {
    this.stackNewest = [];
    this.stackOldest = [];
};

/**
 * Push element x to the back of queue. 
 * @param {number} x
 * @return {void}
 */
MyQueue.prototype.push = function(x) {
    this.stackNewest.push(x); // 对 stackNewest 压栈,其顶部元素总是最新的
};

/**
 * Removes the element from in front of queue and returns that element.
 * @return {number}
 */
MyQueue.prototype.pop = function() {
    if (this.empty()) return -1;
    this.shiftStacks(); // 确保 stackOldest 有当前元素
    return this.stackOldest.pop(); // 对最久元素出栈
};

/**
 * Get the front element.
 * @return {number}
 */
MyQueue.prototype.peek = function() {
    if (this.empty()) return -1;
    this.shiftStacks(); // 确保 stackOldest 有当前元素
    return this.stackOldest[this.stackOldest.length - 1]; // 获取最久的元素
};

/**
 * Returns whether the queue is empty.
 * @return {boolean}
 */
MyQueue.prototype.empty = function() {
    return (this.stackOldest.length + this.stackNewest.length) === 0;
};

MyQueue.prototype.shiftStacks = function() {
	// 将 stackNewest 的元素移动到 stackOldest
	// 一般此操作可以让我们对 stackOldest 进行后续操作
    if (this.stackNewest.length && !this.stackOldest.length){
        while (this.stackNewest.length) {
            this.stackOldest.push(this.stackNewest.pop());
        }
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值