使用一个栈实现
func evalRPN(tokens []string) int {
stack := &Stack{}
for _, s := range tokens {
if n, err := strconv.Atoi(s); err != nil {
// 运算
right, _ := stack.Pop()
left, _ := stack.Pop()
rightNum := right.(int)
leftNum := left.(int)
switch s {
case "+":
stack.Push(leftNum + rightNum)
case "-":
stack.Push(leftNum - rightNum)
case "*":
stack.Push(leftNum * rightNum)
case "/":
stack.Push(leftNum / rightNum)
}
} else {
// 入栈
stack.Push(n)
}
}
res, _ := stack.Pop()
return res.(int)
}
type Stack struct {
data []interface{}
}
func (this *Stack) Len()int {
return len(this.data)
}
func (this *Stack) Push(i interface{}) {
this.data = append([]interface{}{i}, this.data...)
}
func (this *Stack) Peek() interface{} {
return this.data[0]
}
func (this *Stack) Pop() (interface{}, bool) {
if len(this.data) == 0 {
return nil, false
}
i := this.Peek()
this.data = this.data[1:]
return i, true
}