简单的分析+-*/表达式

package main

import (
    "fmt"
    "container/list"
    "strings"
    "strconv"
    //"reflect"
)

func main(){
    opList := list.New()
    valList := list.New()


    fmt.Println("")
    var expression string = "( 4 + 1 ) + ( 6 ) + ( 20 )"

    //isWhile := true
    strList := strings.Split(expression," ")

    for s:= range strList{
        val := strList[s]
        //fmt.Println("index: ", s)

        if val == "("{

        }else if val == "+" || val == "-" || val == "*" || val == "/" || val == "sqrt" || val == "" {
            opList.PushFront(val)
        }else if val == ")"{
            op := opList.Front()
            val := valList.Front()
            valList.Remove(val)

            //fmt.Println("len:",valList.Len())
            //fmt.Println("op: " ,op)
            //fmt.Println("val: ",val)
            //fmt.Println("type:", reflect.TypeOf(val.Value))

            value , ok := val.Value.(int64)

            if ok {

                newVal := valList.Front()
                valList.Remove(newVal)

                if f1,ok1 := newVal.Value.(int64);ok1{
                    //fmt.Println("ok1",op.Value)
                    if op.Value == "+"{
                        val.Value = f1 + value
                    }else if op.Value == "-"{
                        val.Value = f1 - value
                    }else if op.Value == "*"{
                        val.Value = f1 * value
                    }else if op.Value == "/"{
                        val.Value = f1 / value
                    }else if op.Value == "sqrt"{
                        //val.Value = int(valList.Front()) + int(val.Value)
                    }
                }
            }

            valList.PushFront(val.Value)

        }else {
            u,err := strconv.ParseInt(val,10,16)
            if err != nil{
                fmt.Println(err.Error())
            }
            //fmt.Println("值",u)
            valList.PushFront(u)
        }
    }

    for e:= valList.Front(); e!= nil ; e= e.Next()  {
        fmt.Println("结果:" ,e.Value)
    }


}

46_{KDA4}2H[)T5T]OVK[6N[6]

posted @ 2017-01-19 13:52  盘子脸  阅读(422)  评论(0编辑  收藏  举报