【算法】代码随想录训练营Day10打卡,leetcode232.用栈实现队列 225. 用队列实现栈

文章介绍了如何使用栈实现队列以及用队列实现栈的算法,强调理解栈的后进先出(LIFO)和队列的先进先出(FIFO)特性是解决问题的关键。在栈实现队列中,通过两个栈的交互操作达到队列的效果;而在队列实现栈时,利用队列的一次性弹出所有元素再重新入队来模拟栈的出栈操作。
摘要由CSDN通过智能技术生成

【算法】代码随想录训练营Day10打卡,leetcode232.用栈实现队列 225. 用队列实现栈

232.用栈实现队列

力扣链接:https://leetcode.cn/problems/implement-queue-using-stacks/

这道题就其实算是很简单的题了,首先我们要了解栈和队列的特点和区别

栈:
线性表,特点是后进先出,犹如一个垃圾筐,后面进去的垃圾,总是在表面上。
所以出栈的顺序和入栈的顺序是相反的

队列:
线性表,先进先出,犹如一个管道,先进入队列的总是先出队列

所以这道题我们要用一个反向的来实现一个正向的,从数学的角度来思考,那么就是负负得正,我们用两个栈来相互进出栈,就可以轻松的把进出栈相反的顺序给变为正常的顺序了

解法

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

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

/**
* Removes the element from in front of queue and returns that element.
* @return {number}
*/
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();
};

/**
* Get the front element.
* @return {number}
*/
MyQueue.prototype.peek = function() {
   const x = this.pop();
   this.stackOut.push(x);
   return x;
};

/**
* Returns whether the queue is empty.
* @return {boolean}
*/
MyQueue.prototype.empty = function() {
   return !this.stackIn.length && !this.stackOut.length
};

用队列实现栈

力扣链接:https://leetcode.cn/problems/implement-stack-using-queues/
这道题其实,用一个队列就ok,我们在出栈的时候,一次从队列弹出其中的值,直到最后一个是真的弹出,其他的数值保存,当最后一个值弹出后,再把之前保存的值依次放入队列

解法

// 使用一个队列实现
/**
 * Initialize your data structure here.
 */
var MyStack = function() {
    this.queue = [];
};

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

/**
 * Removes the element on top of the stack and returns that element.
 * @return {number}
 */
MyStack.prototype.pop = function() {
    let size = this.queue.length;
    while(size-- > 1) {
        this.queue.push(this.queue.shift());
    }
    return this.queue.shift();
};

/**
 * Get the top element.
 * @return {number}
 */
MyStack.prototype.top = function() {
    const x = this.pop();
    this.queue.push(x);
    return x;
};

/**
 * Returns whether the stack is empty.
 * @return {boolean}
 */
MyStack.prototype.empty = function() {
    return !this.queue.length;
};

今日心得

今日的这两道题主要就是考察你对栈和队列的特性理解度,并不像其他的算法题一般。这道题对于特性理解足够的同学来说可以很快就找到思路。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值