跳到主要内容

面试题03.04.化栈为队

链接:面试题03.04.化栈为队
难度:Easy
标签:栈、设计、队列
简介:实现一个 MyQueue 类,该类用两个栈来实现一个队列。

题解 1 - typescript

  • 编辑时间:2021-03-19
  • 执行用时:88ms
  • 内存消耗:39.2MB
  • 编程语言:typescript
  • 解法介绍:利用两个栈维护。
class MyQueue {
private inStack: number[] = [];
private outStack: number[] = [];
get len() {
return this.inStack.length + this.outStack.length;
}
push(x: number): void {
this.inStack.push(x);
}
pop(): number {
this.outStack.length === 0 && this.numberChange();
return this.outStack.pop()!;
}
peek(): number {
this.outStack.length === 0 && this.numberChange();
return this.outStack[this.outStack.length - 1];
}
empty(): boolean {
return this.len === 0;
}
private numberChange() {
while (this.inStack.length > 0) {
this.outStack.push(this.inStack.pop()!);
}
}
}