借助栈与逆波兰表达式 实现一个计算器,编程语言用的是Golang。
逆波兰表达式可以讲复杂的计算过程转化为简单的操作过程,进而得出答案。 比如 (a+b)*(b-c) 按照逆波兰表达式的规则得到 :ab+bc-*
然后将该表达式的字符以及符号,按照从左到右的顺序,依次入栈,一碰到符号则将栈顶前两个元素取出,做运算然后放入栈内,重复该操作,直到表达式结束。
下面将结合栈与逆波兰表达式写一个简易计算器。
运行命令如下
go run counter.go --expression=\(3-5\)*4-\(5*8\)/3+78*9
代码示例:
package main
import (
"fmt"
"strconv"
"flag"
)
type StackNode struct {
Data interface{}
next *StackNode
}
type LinkStack struct {
top *StackNode
Count int
}
func (this *LinkStack) Init() {
this.top = nil
this.Count = 0
}
func (this *LinkStack) Push(data interface{}) {
var node *StackNode = new(StackNode)
node.Data = data
node.next = this.top
this.top = node
this.Count++
}
func (this *LinkStack) Pop() interface{} {
if this.top == nil {
return nil
}
returnData := this.top.Data
this.top = this.top.next
this.Count--
return returnData
}
//Look up the top element in the stack, but not pop.
func (this