1.用栈实现队列
题目描述
解题思路
1.用两个栈来模拟实现队列的先入先出,定义两个数组stackIn、stackOut两个栈,分别用来模拟入队列和出队列
2.入队列实现没有什么讲究,直接将值入栈stackIn即可,关键是队列的pop操作,需要移除并返回队头元素,因为栈是先入后出,所以我们需要将stackIn栈中的元素弹出来,再push到stackOut栈中,最后从stackOut中弹栈,就实现了栈元素顺序交换,stakcIn入栈 1 2 3 弹栈 3 2 1,stackOut入栈 3 2 1,弹栈 1 2 3,这样入栈出栈顺序就和队列一样了。
3.peek方法可以服用pop方法
4.empty方法只需判断stackIn和stackOut是否都为空即可。
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()) // 将入栈的值一个一个弹出来 再push到出栈中 这样交换了顺序 再从出栈中弹出就是成了出队列的顺序
}
return this.stackOut.pop()
};
/**
* @return {number}
*/
MyQueue.prototype.peek = function() {
const x = this.pop() // 直接调用pop函数 把栈顶元素取出来
this.stackOut.push(x) // 拿到值后再还回去
return x
};
/**
* @return {boolean}
*/
MyQueue.prototype.empty = function() {
return this.stackOut.length == 0 && this.stackIn.length == 0
};
2.用队列实现一个栈
题目描述
解题思路
1.队列是先入先出,而栈是先入后出,用两个队列来实现栈,其中queue1用来保存队列的所有元素,queue2作为副本用来保存queue1中除了队尾元素的其他元素。
2.实现push操作直接将数据入queue1即可
3.pop操作,因为queue1只剩下最后一个队尾元素,是最后进来的,出队列就是最先出来,这就实现了栈的后入先出,再将queue2的副本还原给queue1,这样又保留了原队列的顺序,不影响后续其他操作。
4.top操作直接服用pop操作即可
5.empty操作判断两个队列都不为空即可。
var MyStack = function() {
this.queue1 = []
this.queue2 = []
};
/**
* @param {number} x
* @return {void}
*/
MyStack.prototype.push = function(x) {
this.queue1.push(x) // 入队列
};
/**
* @return {number}
*/
MyStack.prototype.pop = function() {
if(this.queue1.length == 0) { // 当队列1为空时将备份数据还给queue1
[this.queue1,this.queue2] = [this.queue2,this.queue1]
}
while(this.queue1.length>1) {
this.queue2.push(this.queue1.shift()) // 将队列1中除了队尾元素外,全部备份到queue2 剩下最后一个就实现了栈顶元素
}
return this.queue1.shift() // 只剩一个元素 怎么取都一样
};
/**
* @return {number}
*/
MyStack.prototype.top = function() {
const x = this.pop()
this.queue1.push(x)
return x
};
/**
* @return {boolean}
*/
MyStack.prototype.empty = function() {
return !this.queue1.length && !this.queue2.length
};