一、栈与队列理论基础
js的栈和队列都是通过数组来实现的,对一个数组有出栈入栈、出队入队等方法
二、232 用栈实现队列
思路:用一个输入栈一个输出栈来进行模拟
代码:
var MyQueue = function() {
// 一个输入栈
this.stackIn = [];
// 一个输出栈
this.stackOut = [];
};
/**
* @param {number} x
* @return {void}
*/
MyQueue.prototype.push = function(x) {
this.stackIn.push(x);
};
/**
* @return {number}
*/
MyQueue.prototype.pop = function() {
if (this.stackOut.length == 0) {
// 将输入栈的元素全部压入输出栈当中
while (this.stackIn.length) {
var temp = this.stackIn.pop();
this.stackOut.push(temp);
}
}
var x = this.stackOut.pop();
return x;
};
/**
* @return {number}
*/
MyQueue.prototype.peek = function() {
// if (this.stackOut.length !== 0) {
// return this.stackOut[this.stackOut.length - 1];
// }
// else {
// return this.stackIn[0];
// }
// 一种比较方便的做法,不需要遍历
// 先将元素出栈,然后再push回输出栈中
const x = this.pop();
this.stackOut.push(x);
return x;
};
/**
* @return {boolean}
*/
MyQueue.prototype.empty = function() {
if (this.stackIn.length == 0 && this.stackOut.length == 0) {
return true;
}
else {
return false;
}
};
三、225 用队列实现栈
思路:用一个队列就行,主要是删除栈顶的元素,我们把所有的除了最后一个的元素一次从队列头取出,放入尾部,最后再将第一个剩的元素shift出来。
代码:
// 构造函数里面要用this而不是var。。。
var MyStack = function() {
this.queue = [];
};
/**
* @param {number} x
* @return {void}
*/
MyStack.prototype.push = function(x) {
this.queue.push(x);
};
/**
* @return {number}
*/
MyStack.prototype.pop = function() {
for (let i=0; i<this.queue.length-1; i++) {
var temp = this.queue.shift();
this.queue.push(temp);
}
var x = this.queue.shift();
return x;
};
/**
* @return {number}
*/
MyStack.prototype.top = function() {
return this.queue[this.queue.length - 1];
};
/**
* @return {boolean}
*/
MyStack.prototype.empty = function() {
if (this.queue.length) {
return false;
}
else {
return true;
}
};
/**
* 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()
*/
今日学习时长:0.8h左右
总结:今天内容较少,也比较简单,但是需要注意细节,构造函数里面不用var而是用this,怎么会犯这种错误。。。后来想了想应该是最近在写Java。。。