棧_逆波蘭運算式_計算機實現_Golang版本

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。

藉助棧與逆波蘭運算式 實現一個計算機,程式設計語言用的是Golang。

逆波蘭運算式可以講複雜的計算過程轉化為簡單的操作過程,進而得出答案。 比如 (a+b)*(b-c) 按照逆波蘭運算式的規則得到 :ab+bc-*  

然後將該運算式的字元以及符號,按照從左至右的順序,依次入棧,一碰到符號則將棧頂前兩個元素取出,做運算然後放入棧內,重複該操作,直到運算式結束。

下面將結合棧與逆波蘭運算式寫一個簡易計算機。

運行命令如下

go run counter.go --expression=\(3-5\)*4-\(5*8\)/3+78*9

程式碼範例:

package mainimport ("fmt""strconv""flag")type StackNode struct {Data interface{}next *StackNode}type LinkStack struct {top *StackNodeCount int}func (this *LinkStack) Init() {this.top = nilthis.Count = 0}func (this *LinkStack) Push(data interface{}) {var node *StackNode = new(StackNode)node.Data = datanode.next = this.topthis.top = nodethis.Count++}func (this *LinkStack) Pop() interface{} {if this.top == nil {return nil}returnData := this.top.Datathis.top = this.top.nextthis.Count--return returnData}//Look up the top element in the stack, but not pop.func (this *LinkStack) LookTop() interface{} {if this.top == nil {return nil}return this.top.Data}var str *string = flag.String("expression", "", "")func main() {flag.Parse()fmt.Println(*str)fmt.Println(Count(*str))}func Count(data string) float64 {//TODO 檢查字串輸入var arr []string = generateRPN(data)return calculateRPN(arr)}func calculateRPN(datas []string) float64 {var stack LinkStackstack.Init()for i := 0; i < len(datas); i++ {if isNumberString(datas[i]) {if f, err := strconv.ParseFloat(datas[i], 64); err != nil {panic("operatin process go wrong.")} else {stack.Push(f)}} else {p1 := stack.Pop().(float64)p2 := stack.Pop().(float64)p3 := normalCalculate(p2, p1, datas[i])stack.Push(p3)}}res := stack.Pop().(float64)return res}func normalCalculate(a,b float64, operation string) float64 {switch operation{case "*":return a * bcase "-":return a - bcase "+":return a + bcase "/":return a / bdefault:panic("invalid operator")}}func generateRPN(exp string) []string {var stack LinkStackstack.Init()var spiltedStr []string = convertToStrings(exp)var datas []stringfor i := 0; i < len(spiltedStr); i++ { // 遍曆每一個字元tmp := spiltedStr[i] //當前字元if !isNumberString(tmp) { //是否是數字// 四種情況入棧// 1 左括弧直接入棧// 2 棧內為空白直接入棧// 3 棧頂為左括弧,直接入棧// 4 當前元素不為右括弧時,在比較棧頂元素與當前元素,如果當前元素大,直接入棧。if tmp == "(" ||stack.LookTop() == nil || stack.LookTop().(string) == "(" ||( compareOperator(tmp, stack.LookTop().(string)) == 1 && tmp != ")" ) {stack.Push(tmp)} else { // ) priorityif tmp == ")" { //當前元素為右括弧時,提取操作符,直到碰見左括弧for {if pop := stack.Pop().(string); pop == "(" {break} else {datas = append(datas, pop)}}} else { //當前元素為操作符時,不斷地與棧頂元素比較直到遇到比自己小的(或者棧空了),然後入棧。for {pop := stack.LookTop()if pop != nil && compareOperator(tmp, pop.(string)) != 1 {datas = append(datas, stack.Pop().(string))} else {stack.Push(tmp)break}}}}} else {datas = append(datas, tmp)}}//將棧內剩餘的操作符全部彈出。for {if pop := stack.Pop(); pop != nil {datas = append(datas, pop.(string))} else {break}}return datas}// if return 1, o1 > o2.// if return 0, o1 = 02// if return -1, o1 < o2func compareOperator(o1, o2 string) int {// + - * /var o1Priority intif o1 == "+" || o1 == "-" {o1Priority = 1} else {o1Priority = 2}var o2Priority intif o2 == "+" || o2 == "-" {o2Priority = 1} else {o2Priority = 2}if o1Priority > o2Priority {return 1} else if o1Priority == o2Priority {return 0} else {return -1}}func isNumberString(o1 string) bool {if o1 == "+" || o1 == "-" || o1 == "*" || o1 == "/" || o1 == "(" || o1 == ")" {return false} else {return true}}func convertToStrings(s string) []string {var strs []stringbys := []byte(s)var tmp stringfor i := 0; i < len(bys); i++ {if !isNumber(bys[i]) {if tmp != "" {strs = append(strs, tmp)tmp = ""}strs = append(strs, string(bys[i]))} else {tmp = tmp+string(bys[i])}}strs = append(strs, tmp)return strs}func isNumber(o1 byte) bool {if o1 == '+' || o1 == '-' || o1 == '*' || o1 == '/' || o1 == '(' || o1 == ')' {return false} else {return true}}


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.