题
现在有个Q队列和栈A,栈B,栈只有两个方法,push()和pop(), 队列也只有两个方法,push()和pull(),队列的进和出都只能通过A和B的push和pop实现。
// 大概举个例子
const Q = {
a = new A(),
b = new B(),
push() {
},
pull() {
}
}
解
const Q = {
a: [], // 先放
b: [], // 后放
push(value) {
const lengthA = this.a.length;
const lengthB = this.b.length;
if (lengthA === lengthB) {
this.a.push(value);
} else {
this.b.push(value);
}
return lengthA + lengthB + 1;
},
pull() {
const lengthA = this.a.length;
if (!lengthA) return undefined;
const func = (popArray, pushArray, forLength) => {
for (let i = 0; i < forLength; i++) {
const value = popArray.pop();
pushArray.push(value);
}
};
func(this.a, this.b, lengthA - 1);
const result = this.a.pop();
func(this.b, this.a, lengthA - 1);
const { a } = this;
this.a = this.b;
this.b = a;
return result;
},
};
Q.push('a');
Q.push('b');
Q.push('c');
Q.pull(); // a
Q.pull(); // b
Q.pull(); // c