YuJian
3 years ago
1 changed files with 37 additions and 1 deletions
@ -1 +1,37 @@
@@ -1 +1,37 @@
|
||||
## 用两个栈实现一个队列 |
||||
|
||||
```javascript |
||||
class StackQueue { |
||||
private stack1: number[] = []; |
||||
private stack2: number[] = []; |
||||
add(value: number) { |
||||
this.stack1.push(value); |
||||
} |
||||
popup() { |
||||
if (!this.stack1.length) return; |
||||
while (this.stack1.length) { |
||||
const stackValue = this.stack1.pop(); |
||||
this.stack2.push(stackValue!); |
||||
} |
||||
const popValue = this.stack2.pop(); |
||||
while (this.stack2.length) { |
||||
const stackValue = this.stack2.pop(); |
||||
this.stack1.push(stackValue!); |
||||
} |
||||
|
||||
|
||||
|
||||
return popValue; |
||||
|
||||
} |
||||
|
||||
|
||||
|
||||
get length() { |
||||
|
||||
return this.stack1.length; |
||||
|
||||
} |
||||
|
||||
} |
||||
``` |
Loading…
Reference in new issue