leetcode/lcci/03.04.Implement Queue using.../Solution.ts

45 lines
813 B
TypeScript

class MyQueue {
stk1: number[];
stk2: number[];
constructor() {
this.stk1 = [];
this.stk2 = [];
}
push(x: number): void {
this.stk1.push(x);
}
pop(): number {
this.move();
return this.stk2.pop();
}
peek(): number {
this.move();
return this.stk2.at(-1);
}
empty(): boolean {
return !this.stk1.length && !this.stk2.length;
}
move(): void {
if (!this.stk2.length) {
while (this.stk1.length) {
this.stk2.push(this.stk1.pop()!);
}
}
}
}
/**
* Your MyQueue object will be instantiated and called as such:
* var obj = new MyQueue()
* obj.push(x)
* var param_2 = obj.pop()
* var param_3 = obj.peek()
* var param_4 = obj.empty()
*/