1.用栈实现队列 leetcode232
队列的特性是(先入先出),而栈的特性是(先入后出)
需要用两个栈来模拟队列的特性,一个栈为入队栈,一个栈为出对栈
入栈时,直接pop进去
出栈时,如果出栈的数据为空时,需要把入栈中的所有数据导入进去,在弹出(如果没有全部导进去 会破坏整体的顺序,顺序乱了,无法正确的弹出数据)。如果不为空,则直接从出栈弹出数据就可以了。
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) {
return this.stackOut.pop()
}
// 如果入栈中有数据,就全部导入到出栈里,避免顺序出现问题
while (this.stackIn.length) {
this.stackOut.push(this.stackIn.pop())
}
return this.stackOut.pop()
};
/**
* @return {number}
*/
MyQueue.prototype.peek = function () {
// 复用pop函数,peek只取值,不用弹出,所以再push进去
const x = this.pop();
this.stackOut.push(x);
return x
};
/**
* @return {boolean}
*/
MyQueue.prototype.empty = function () {
return !this.stackIn.length && !this.stackOut.length
};
2.用队列实现栈 leetcode225
只需要一个队列就可模拟栈
一个队列在模拟栈弹出元素的时候只要将队列头部的元素(除了最后一个元素外) 重新添加到队列尾部,此时再去弹出元素就是栈的顺序了
1-》2-》3 可以将前面两个弹出来然后push到队尾 3-》1=》2 然后拿到3, 队列只剩下2,1 在将1弹出push到队尾 拿到2,以此类推
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 () {
let size = this.queue.length
// 不断弹出队首的,放到队尾去
while (size > 1) {
size--;
this.queue.push(this.queue.shift())
}
return this.queue.shift()
};
/**
* @return {number}
*/
MyStack.prototype.top = function () {
let x = this.pop();
this.queue.push(x)
return x
};
/**
* @return {boolean}
*/
MyStack.prototype.empty = function () {
return this.queue.length == 0
};