题目考察的知识点
- 栈
题目解答方法的文字分析
- 略
本题解析所用的编程语言
- JavaScript
完整且正确的编程代码
function max_weight_cow( op , vals ) {
// write code here
let stack = [-1]
let res = []
for(let i= 1;i<op.length;i++){
if(op[i]=='push'){
res.push(vals[i][1])
stack.push(-1)
}else if(op[i]== 'pop'&&res.length>0){
res.pop()
stack.push(-1)
}else if(op[i]=='getMax'){
stack.push(Math.max(...res))
}else if(op[i]=='top'){
stack.push(res[res.length-1])
}
}
return stack
}、
这段代码定义了一个名为max_weight_cow的函数,它接受两个参数op和vals。
函数内部使用了一个stack数组和一个res数组来模拟栈的行为。首先,将-1压入stack数组中作为初始值。
然后,函数使用一个循环来遍历op数组。在每次迭代中,根据op[i]的不同执行不同的操作:
- 如果
op[i]等于push,将vals[i][1]压入res数组,并向stack数组中压入-1。 - 如果
op[i]等于pop且res数组的长度大于0,将res数组的末尾元素弹出,并向stack数组中压入-1。 - 如果
op[i]等于getMax,将res数组中的最大值(使用Math.max(...res))压入stack数组。 - 如果
op[i]等于top,将res数组中的最后一个元素压入stack数组。
循环结束后,将stack数组作为函数的返回值。
这段代码的功能是模拟一个栈,并支持push、pop、getMax和top操作。例如,通过传入['push', 'push', 'getMax', 'pop', 'top']和[[], [5], [], [], []]作为参数,可以得到[-1, -1, 5, -1, 5]作为返回值。

京公网安备 11010502036488号