杨乐乐
Never too late

Follow

Never too late

Follow
Day 10 栈与队列 - 用栈实现队列

Day 10 栈与队列 - 用栈实现队列

JS中使用数组来实现栈和队列

杨乐乐's photo
杨乐乐
·Jan 20, 2023·

1 min read

Table of contents

  • 232. 用栈实现队列
  • 225. 用队列实现栈

232. 用栈实现队列

class MyQueue {
    private stackIn: number[]
    private stackOut: number[]

    constructor() {
        this.stackIn = [];
        this.stackOut = [];
    } 

    push(x: number): void {
        this.stackIn.push(x);
    }

    pop(): number {
        if (this.stackOut.length === 0) {
            while (this.stackIn.length) {
                this.stackOut.push(this.stackIn.pop())
            }
        }
        return this.stackOut.pop();
    }

    peek(): number {
        let temp: number = this.pop();
        this.stackOut.push(temp);
        return temp;
    }

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

225. 用队列实现栈

class MyStack {
    private queue: number[]
    constructor() {
        this.queue = [];
    }

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

    pop(): number {
        return this.queue.pop();
    }

    top(): number {
        let temp = this.pop();
        this.push(temp);
        return temp;
    }

    empty(): boolean {
        return this.queue.length === 0;
    }
}
 
Share this