232. 用栈实现队列
class MyQueue {
stackIn: number[] = []
stackOut: number[] = []
constructor(){
}
push(x: number): void {
while (this.stackOut.length){
this.stackIn.push(this.stackOut.pop())
}
this.stackIn.push(x)
}
pop(): number {
while (this.stackIn.length){
this.stackOut.push(this.stackIn.pop())
}
return this.stackOut.pop()
}
peek(): number {
const result: number = this.pop()
this.stackOut.push(result)
return result
}
empty(): boolean {
return this.stackIn.length === 0 && this.stackOut.length === 0
}
}
重点在于push() 和 pop()的过程,做哪个方法就要向相应的栈里挪元素
peek()遵循代码复用原则,相当于pop()了一下再push进去那个pop的元素
反思
在empty()
中,不能用 this.stackIn === []
因为数组是对象,不能用全等号比较
225. 用队列实现栈
class MyStack {
private queue: number[] = []
constructor() {
}
push(x: number): void {
this.queue.push(x)
}
pop(): number {
for (let i: number = 0; i < this.queue.length - 1; i++) {
this.queue.push(this.queue.pop())
}
return this.queue.pop()
}
top(): number {
const result: number = this.queue.pop()
this.queue.push(result)
return result
}
empty(): boolean {
return this.queue.length === 0
}
}
- 重点在于pop()的方式:压入 弹出的元素直到最后一个元素(栈顶元素),这时再弹出的元素就是栈顶元素。
- top() 同样可以复用pop()
- 动笔画图,不能懒,纸上还原动态过程