mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 16:54:50 +08:00
Merge pull request #1048 from xiaofei-2020/stack3
添加(0225.用队列实现栈.md):增加typescript版本
This commit is contained in:
@ -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
|
||||||
|
|
||||||
```Swift
|
```Swift
|
||||||
// 定义一个队列数据结构
|
// 定义一个队列数据结构
|
||||||
class Queue {
|
class Queue {
|
||||||
|
Reference in New Issue
Block a user