题解 | #包含min函数的栈#

包含min函数的栈

https://www.nowcoder.com/practice/4c776177d2c04c2494f2555c9fcc1e49

package main

var  stackAll []int // 存储栈中的元素
var  stackMin []int // 存储每个栈中的最小值

func Push(node int) {
    // write code here
    stackAll = append(stackAll, node)
    if len(stackMin) == 0 || node <= stackMin[len(stackMin)-1] {
        stackMin = append(stackMin, node)
    }    
}
func Pop() {
    // write code here
    if stackAll[len(stackAll)-1] == stackMin[len(stackMin)-1] {
        stackMin = stackMin[:len(stackMin)-1]
    } 
    stackAll = stackAll[:len(stackAll)-1]

}

func Top() int {
    // write code here
    return stackAll[len(stackAll)-1]
}
func Min() int {
    // write code here
    return stackMin[len(stackMin) - 1]
}

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务