代码随想录算法营JS/TS版Day10:栈与队列(一)| LeetCode 232. 用栈实现队列, 225. 用队列实现栈

232. 用栈实现队列

class MyQueue {
    stackIn: number[] = []
    stackOut: number[] = []
    constructor(){
    }
    push(x: number): void {
        while (this.stackOut.length){
            this.stackIn.push(this.stackOut.pop())
        }
        this.stackIn.push(x)
    }

    pop(): number {
        while (this.stackIn.length){
            this.stackOut.push(this.stackIn.pop())
        }
        return this.stackOut.pop()
    }

    peek(): number {
        const result: number = this.pop()
        this.stackOut.push(result)
        return result
    }

    empty(): boolean {
        return this.stackIn.length === 0 && this.stackOut.length === 0
    }
}

重点在于push() 和 pop()的过程,做哪个方法就要向相应的栈里挪元素

peek()遵循代码复用原则,相当于pop()了一下再push进去那个pop的元素

反思

empty() 中,不能用 this.stackIn === [] 因为数组是对象,不能用全等号比较

225. 用队列实现栈

class MyStack {
    private queue: number[] = []

    constructor() {

    }

    push(x: number): void {
        this.queue.push(x)
    }

    pop(): number {
        for (let i: number = 0; i < this.queue.length - 1; i++) {
            this.queue.push(this.queue.pop())
        }
        return this.queue.pop()
    }

    top(): number {
        const result: number = this.queue.pop()
        this.queue.push(result)
        return result
    }

    empty(): boolean {
        return this.queue.length === 0
    }
}
  1. 重点在于pop()的方式:压入 弹出的元素直到最后一个元素(栈顶元素),这时再弹出的元素就是栈顶元素。
  2. top() 同样可以复用pop()
  3. 动笔画图,不能懒,纸上还原动态过程
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值