js练习-两个栈实现队列
题
现在有个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
本博客所记录的文章,主要是从网络收集的,有一些因为经过多次转载,所以出处已经不知,若是侵权,请通知我,我及时修改。本博客主要是用来记录我对所写文章的理解,若有错误,请大家指点,相互学习!