From 7037fb2877da6406d690e7bf3160da5c2b5dc673 Mon Sep 17 00:00:00 2001 From: Steve2020 <841532108@qq.com> Date: Fri, 21 Jan 2022 17:25:00 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=880225.=E7=94=A8?= =?UTF-8?q?=E9=98=9F=E5=88=97=E5=AE=9E=E7=8E=B0=E6=A0=88.md=EF=BC=89?= =?UTF-8?q?=EF=BC=9A=E5=A2=9E=E5=8A=A0typescript=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0225.用队列实现栈.md | 73 +++++++++++++++++++++++++++++ 1 file changed, 73 insertions(+) diff --git a/problems/0225.用队列实现栈.md b/problems/0225.用队列实现栈.md index fdb544a6..961fad38 100644 --- a/problems/0225.用队列实现栈.md +++ b/problems/0225.用队列实现栈.md @@ -598,7 +598,80 @@ MyStack.prototype.empty = function() { ``` +TypeScript: + +版本一:使用两个队列模拟栈 + +```typescript +class MyStack { + private queue: number[]; + private tempQueue: number[]; + constructor() { + this.queue = []; + this.tempQueue = []; + } + + push(x: number): void { + this.queue.push(x); + } + + pop(): number { + for (let i = 0, length = this.queue.length - 1; i < length; i++) { + this.tempQueue.push(this.queue.shift()!); + } + let res: number = this.queue.pop()!; + let temp: number[] = this.queue; + this.queue = this.tempQueue; + this.tempQueue = temp; + return res; + } + + top(): number { + let res: number = this.pop(); + this.push(res); + return res; + } + + empty(): boolean { + return this.queue.length === 0; + } +} +``` + +版本二:使用一个队列模拟栈 + +```typescript +class MyStack { + private queue: number[]; + constructor() { + this.queue = []; + } + + push(x: number): void { + this.queue.push(x); + } + + pop(): number { + for (let i = 0, length = this.queue.length - 1; i < length; i++) { + this.queue.push(this.queue.shift()!); + } + return this.queue.shift()!; + } + + top(): number { + let res: number = this.pop(); + this.push(res); + return res; + } + + empty(): boolean { + return this.queue.length === 0; + } +} +``` + Swift + ```Swift // 定义一个队列数据结构 class Queue {