232.用栈实现队列
题目链接:https://leetcode.cn/problems/implement-queue-using-stacks/
var MyQueue = function() {
// 用数组实现栈的功能
this.stackIn=[]
this.stackOut=[]
};
MyQueue.prototype.push = function(x) {
//入栈
this.stackIn.push(x)
}
//出栈
MyQueue.prototype.pop = function() {
const size=this.stackOut.length
if(size){
return this.stackOut.pop()
}
while(this.stackIn.length){
this.stackOut.push(this.stackIn.pop())
}
return this.stackOut.pop()
};
MyQueue.prototype.peek = function() {
const x=this.pop()
this.stackOut.push(x)
return x
};
MyQueue.prototype.empty = function() {
return !this.stackOut.length && !this.stackIn.length
};
看完视频所学:
1.javascript中没有栈,可以用数组来实现栈
2.基础知识:
队列是先进先出,栈是先进后出
3.用栈来实现队列即把先进后出变为先进先出
4.这里用两个栈来实现次功能
5.入栈还是一样依次进内容放入,而出栈操作,先加入一个栈,让第一个栈进行出栈操作进入新加的栈中,然后将新栈中的元素依次弹出,即可实现先进先出功能。
6.peek是返回队列开头的元素,和出栈一样,复用一下出栈的函数,只不过不需要弹出即可。
注意点:
复用弹出函数的时候千万不要再去把弹出函数复制一遍。
225.用队列实现栈
题目链接:https://leetcode.cn/problems/implement-stack-using-queues/
var MyStack = function() {
this.queue=[]
};
MyStack.prototype.push = function(x) {
this.queue.push(x)
};
MyStack.prototype.pop = function() {
let size=this.queue.length
// 将size-1的元素弹出重新加入,即只留下最后一个元素。
// size-- >1的操作是到最后一个数的时候停止,价格最后一个数弹出。前面的时候放在最后的末尾。
while(size-- >1){
this.queue.push(this.queue.shift())
}
//返回除了最后一个元素剩下的所有元素。即将最后一个元素弹出,实现了后进先出的效果
return this.queue.shift()
};
MyStack.prototype.top = function() {
const x=this.pop()
this.queue.push(x)
return x
};
MyStack.prototype.empty = function() {
return !this.queue.length
};
看完视频所学:
1.可以用两个队列实现栈,但这里用一个队列也可以实现,所以更倾向于来写用一个队列来实现。
2.入栈依旧是依次放入
3.出栈为先进后出,要把先进先出变为先进后出
4.将先进来的元素依次取出放入最后一个元素后面,依次执行。即只保留最后一个元素然后弹出,就可实现先进后出的操作。
注意点:
1.shift()函数:用于把数组的第一个元素从其中删除,并返回第一个元素的值。