用两个栈实现一个队列
题目
请用两个栈,来实现队列的功能,实现功能 add delete length 。
队列 Queue
栈,先进后出
队列,先进先出,API 包括
- add
- delete
- length
class MyQueue {
stack1 = [];
stack2 = [];
add(n) {
this.stack1.push(n);
}
delete() {
let res;
const stack1 = this.stack1;
const stack2 = this.stack2;
while (stack1.length) {
const n = stack1.pop();
if (n != null) {
stack2.push(n);
}
}
res = stack2.pop();
while (stack2.length) {
const n = stack2.pop();
if (n != null) {
stack1.push(n);
}
}
return res || null;
}
get length() {
return this.stack1.length;
}
}