Skip to content

Commit 25cd24c

Browse files
authoredJun 2, 2021
feat: add typescript solution to locf problem: No.09. Implement Queue using Stacks (doocs#428)
1 parent 572e2e4 commit 25cd24c

File tree

2 files changed

+75
-0
lines changed

2 files changed

+75
-0
lines changed
 

‎lcof/面试题09. 用两个栈实现队列/README.md

+40
Original file line numberDiff line numberDiff line change
@@ -206,6 +206,46 @@ public:
206206
};
207207
```
208208

209+
### **TypeScript**
210+
211+
```ts
212+
class CQueue {
213+
private stack1: number[];
214+
private stack2: number[];
215+
constructor() {
216+
this.stack1 = [];
217+
this.stack2 = [];
218+
}
219+
220+
appendTail(value: number): void {
221+
this.stack1.push(value);
222+
if (this.stack2.length == 0) {
223+
this.move();
224+
}
225+
}
226+
227+
move(): void {
228+
while (this.stack1.length != 0) {
229+
this.stack2.push(this.stack1.pop());
230+
}
231+
}
232+
233+
deleteHead(): number {
234+
if (this.stack2.length == 0) {
235+
this.move();
236+
}
237+
return this.stack2.length == 0 ? -1 : this.stack2.pop();
238+
}
239+
}
240+
241+
/**
242+
* Your CQueue object will be instantiated and called as such:
243+
* var obj = new CQueue()
244+
* obj.appendTail(value)
245+
* var param_2 = obj.deleteHead()
246+
*/
247+
```
248+
209249
### **...**
210250

211251
```
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
class CQueue {
2+
private stack1: number[];
3+
private stack2: number[];
4+
constructor() {
5+
this.stack1 = [];
6+
this.stack2 = [];
7+
}
8+
9+
appendTail(value: number): void {
10+
this.stack1.push(value);
11+
if (this.stack2.length == 0) {
12+
this.move();
13+
}
14+
}
15+
16+
move(): void {
17+
while (this.stack1.length != 0) {
18+
this.stack2.push(this.stack1.pop());
19+
}
20+
}
21+
22+
deleteHead(): number {
23+
if (this.stack2.length == 0) {
24+
this.move();
25+
}
26+
return this.stack2.length == 0 ? -1 : this.stack2.pop();
27+
}
28+
}
29+
30+
/**
31+
* Your CQueue object will be instantiated and called as such:
32+
* var obj = new CQueue()
33+
* obj.appendTail(value)
34+
* var param_2 = obj.deleteHead()
35+
*/

0 commit comments

Comments
 (0)
Please sign in to comment.