示例#1
0
func pre2stuf(exps []string) (exps2 []string) {
	st1 := stack.NewStack()
	st2 := stack.NewStack()

	for _, exp := range exps {
		if isOperate(exp) {
			if op, ok := isPop(st1, exp); ok {
				for _, s := range op {
					st2.Push(s)
				}
			}
			if exp == ")" {
				continue
			}
			st1.Push(exp)
		} else {
			st2.Push(exp)
		}
	}

	// fmt.Print(cur.Value)
	for !st1.IsEmpty() {
		st2.Push(st1.Pop().Value)
	}

	for _, e := range st2.Elements {
		s, _ := e.Value.(string)
		exps2 = append(exps2, s)
	}

	// fmt.Println(exps2)
	return
}
示例#2
0
func CreateExpressionTree(exps []string) Node {
	st := stack.NewStack()
	for _, s := range exps {
		if isOperate(s) {
			operateNode := CreateOperateNode(s)
			right, _ := st.Pop().Value.(Node)
			left, _ := st.Pop().Value.(Node)
			operateNode.setRight(right)
			operateNode.setLeft(left)
			// fmt.Println(operateNode)
			st.Push(operateNode)
		} else {
			num, _ := strconv.Atoi(s)
			numberNode := CreateNumberNode(num)
			st.Push(numberNode)
		}
	}
	if st.Len() != 1 {
		panic("CreateExpressionTree error")
	}
	node, _ := st.Pop().Value.(Node)
	// fmt.Println(node)
	return node
}