232.用栈实现队列
225.用队列实现栈
232. 用栈实现队列
- 我的思路:stk1为缓冲区,stk2为队列区
- 注意点:实现stk1的元素传递到stk2时,不可用以长度为条件的for循环,因为每次pop数组长度都在变!
var MyQueue = function() {
this.stk1 = [];
this.stk2 = [];
};
MyQueue.prototype.push = function(x) {
this.stk1.push(x);
};
MyQueue.prototype.pop = function() {
if (this.stk2.length === 0) {
while (this.stk1.length > 0) {
this.stk2.push(this.stk1.pop());
}
}
const n2 = this.stk2.pop();
return n2;
};
MyQueue.prototype.peek = function() {
const n = this.pop();
this.stk2.push(n);
return n;
};
MyQueue.prototype.empty = function() {
if (this.stk1.length + this.stk2.length === 0) return true;
return false;
};
225. 用队列实现栈
- 感想:用队列shift调整位置实现pop好巧妙啊!
var MyStack = function() {
this.q = [];
};
MyStack.prototype.push = function(x) {
this.q.push(x);
};
MyStack.prototype.pop = function() {
let len = this.q.length;
len--;
while (len--) {
this.q.push(this.q.shift());
}
return this.q.shift();
};
MyStack.prototype.top = function() {
return this.q[this.q.length - 1];
};
MyStack.prototype.empty = function() {
return this.q.length === 0;
};