题解 | #设计getMin功能的栈#
设计getMin功能的栈
http://www.nowcoder.com/practice/05e57ce2cd8e4a1eae8c3b0a7e9886be
package main
import (
"bufio"
"fmt"
"os"
"strconv"
"strings"
)
func main() {
var N int
fmt.Scanln(&N)
//初始化栈结构
gsm := initStack()
sc := bufio.NewScanner(os.Stdin)
for i := 0; i < N; i++ {
sc.Scan()
curline := strings.Split(sc.Text(), " ")
operation := curline[0]
switch operation {
case "push":
n, _ := strconv.Atoi(curline[1])
gsm.push(n)
case "pop":
fmt.Println(gsm.pop())
case "getMin":
fmt.Println(gsm.getMin())
}
}
}
type getMinStack struct {
numStack []int //记录数据的栈
minStack []int //记录最小值的栈
}
//初始化
func initStack() getMinStack {
return getMinStack{[]int{}, []int{}}
}
func (this *getMinStack) push(n int) {
l := len(this.numStack)
this.numStack = append(this.numStack, n)
if l == 0 {
this.minStack = append(this.minStack, n)
return
}
curMin := this.minStack[l-1]
if curMin > n {
this.minStack = append(this.minStack, n)
} else {
this.minStack = append(this.minStack, curMin)
}
}
func (this *getMinStack) pop() int {
l := len(this.numStack)
n := this.numStack[l-1]
this.numStack = this.numStack[0 : l-1]
this.minStack = this.minStack[0 : l-1]
return n
}
func (this *getMinStack) getMin() int {
return this.minStack[len(this.minStack)-1]
}