用到的函数:
push()在数组末尾添加元素
shift()删除数组第一个元素
实现先进后出的原理:this.q.push(this.q.shift())

//创建1个队列
var MyStack = function() {
this.q=[]
};
/**
* @param {number} x
* @return {void}
*/
MyStack.prototype.push = function(x) {
this.q.push(x)
};
/**
* @return {number}
*/
//先进后出,返回数组末尾的元素
MyStack.prototype.pop = function() {
let n=this.q.length-1
//循环到最后一个
while(n-->0){
//把删除的第一个加入到队列末尾
this.q.push(this.q.shift())
}
return this.q.shift()
};
/**
* @return {number}
*/
//栈顶是数组末尾位置
MyStack.prototype.top = function() {
//获得末尾元素
const x=this.pop()
//再还回去
this.q.push(x)
return x
};
/**
* @return {boolean}
*/
MyStack.prototype.empty = function() {
return !this.q.length
};
这篇博客介绍了一种使用JavaScript实现先进后出(FIFO)队列栈的方法。通过结合push和shift函数,作者创建了一个MyStack类,其中push方法用于添加元素,pop方法实现从队列末尾移除元素并返回,top方法返回队列顶部(即末尾)的元素而不删除,而empty方法检查队列是否为空。这个实现可以作为理解数据结构和JavaScript操作数组的实例。
691

被折叠的 条评论
为什么被折叠?



