理论基础
栈是后入先出(放塑料椅子)
队列是先入先出(核酸排队,先入的先做)
var MyQueue = function() { //MyQueue对象
//1.创建两个栈
this.stack_in = []; //stack为空
this.stack_out = [];
};
/**
* @param {number} x
* @return {void}
*/
MyQueue.prototype.push = function(x) {//将元素 x 推到队列的末尾
this.stack_in.push(x);
};
/**
* @return {number}
*/
MyQueue.prototype.pop = function() {//从队列的开头移除并返回元素
const n=this.stack_out.length
if(n) //如果out里有值,直接出
return this.stack_out.pop()
while(this.stack_in.length){ //把in里的东西倒转到out
this.stack_out.push(this.stack_in.pop()); //可in里面的东西没了啊
}
return this.stack_out.pop()
};
/**
* @return {number}
*/
MyQueue.prototype.peek = function() { //返回队列开头的元素
const x=this.pop(); //调用队列的pop()算法
this.stack_out.push(x); //再放进去
return x
};
/**
* @return {boolean}
*/
MyQueue.prototype.empty = function() {
return !this.stack_in.length && !this.stack_out.length//in为0并且out为0返回true
};
/**
* Your MyQueue object will be instantiated and called as such:
* var obj = new MyQueue()
* obj.push(x)
* var param_2 = obj.pop()
* var param_3 = obj.peek()
* var param_4 = obj.empty()
*/
第一想法
思想还可以,但写出来不行,this.pop();
收获
- this.stack_in = [];
this的作用
225. 用队列实现栈
两个队列:
var MyStack = function() {//实现后入先出(LIFO)的栈
this.queue1 = []; //创建两个队列(先入先出),用push()和shift()(头部弹出)模拟
this.queue2 = [];
};
/**
* Push element x onto stack.
* @param {number} x
* @return {void}
*/
MyStack.prototype.push = function(x) {
this.queue1.push(x);
};
/**
* Removes the element on top of the stack and returns that element.
* @return {number}
*/
//1:1 2 3 4
//2:1 2 3
//1:4
MyStack.prototype.pop = function() {
// 减少两个队列交换的次数, 只有当queue1为空时,交换两个队列
if(!this.queue1.length) {
[this.queue1, this.queue2] = [this.queue2, this.queue1];
}
while(this.queue1.length > 1) { //每一次都是1出
this.queue2.push(this.queue1.shift());
}
return this.queue1.shift();
};
/**
* Get the top element.
* @return {number}
*/
MyStack.prototype.top = function() {
const x = this.pop();
this.queue1.push(x);
return x;
};
/**
* Returns whether the stack is empty.
* @return {boolean}
*/
MyStack.prototype.empty = function() {
return !this.queue1.length && !this.queue2.length;
};
一个队列:
var MyStack = function() {
this.queue=[]
};
/**
* @param {number} x
* @return {void}
*/
MyStack.prototype.push = function(x) {
this.queue.push(x)
};
/**
* @return {number}
*/
// 1 2 3 4
MyStack.prototype.pop = function() {
this.queue.reverse()
let x=this.queue.shift()
this.queue.reverse()
return x
};
/**
* @return {number}
*/
MyStack.prototype.top = function() {
let x=this.pop()
this.push(x)
return x
};
/**
* @return {boolean}
*/
MyStack.prototype.empty = function() {
if(this.queue.length===0)
return true
return false
};
/**
* Your MyStack object will be instantiated and called as such:
* var obj = new MyStack()
* obj.push(x)
* var param_2 = obj.pop()
* var param_3 = obj.top()
* var param_4 = obj.empty()
*/
第一想法
想着用上一道题的方法把它反过来,发现反过来是一样的。
收获
- 互换的应用: [this.queue1, this.queue2] = [this.queue2, this.queue1];