1.关于如何运行.ts代码,请转至
VS Code如何运行.ts文件(TypeScript基础环境搭建)
2.代码
export class MyQueue {
private stack1: number[] = [];
private stack2: number[] = [];
// 入队
add(n: number) {
this.stack1.push(n);
}
// 出队
delete(): number | null {
let res;
const stack1 = this.stack1;
const stack2 = this.stack2;
// 1.将stack1所有元素移动到stack2中
while (stack1.length) {
const n = stack1.pop();
if (n != null) {
stack2.push(n);
}
}
// 2.删除stack2栈顶元素
res = stack2.pop();
// 3.将stack2中所有元素移动到stack1中
while (stack2.length) {
const n = stack2.pop();
if (n != null) {
stack1.push(n);
}
}
return res || null;
}
get length(): number {
return this.stack1.length;
}
}
3.功能测试
const q = new MyQueue();
q.add(100);
q.add(200);
q.add(300);
console.log(q.length); // 3
console.log(q.delete()); // 100
console.log(q.length); // 2
4.过程演示