Go 程序打印星号而不是实际字符

Go program prints asterisks instead of actual characters

我正在编写一个程序,将后缀表达式转换为其前缀形式(因此它应该将此“ABC/-AK/L-*”转换为此“*-A/BC-/AKL”。规则是简单:如果它是一个字母或一个数字(操作数),那么它被压入堆栈,如果它是一个运算符,那么最后两个字符(比如 op1(最后一个)和 op2(最后一个之后的那个))堆栈被弹出,然后与运算符 (temp = operator + op2 + op1) 连接,然后将此 temp 推入堆栈。

问题是当使用 pop 时,操作数变成星号,我不知道为什么。也许需要指针?有人可以告诉我我做错了什么吗?非常感谢!

输入:“ABC/-AK/L-*”

预期输出:“*-A/BC-/AKL”

观察到的输出:“[***]”


import (
    "fmt"
)

type Stack []string

func (s *Stack) isEmpty() bool {
    return len(*s) == 0
}

func (s *Stack) push(value string) {
    *s = append(*s, value)
}

func (s *Stack) pop() (string, bool) {
    if s.isEmpty() {
        return "", false
    } else {
        elementIndex := len(*s) - 1
        element := (*s)[elementIndex]
        *s = (*s)[:elementIndex]
        return element, true
    }
}

func isOperator(character string) bool {
    switch character {
    case "+", "-", "*", "/":
        return true
    default:
        return false
    }

}

func input() {
    var stack Stack
    fmt.Print("Please input the equation without spaces: \n")
    input := "ABC/-AK/L-*"


    for _, character := range input {
        valueCheck := isOperator(string(character))
        if valueCheck == true {
            operand1 := input[len(input)-1]
            stack.pop()
            operand2 := input[len(input)-1]
            stack.pop()

            var temp string
            temp = string(character) + string(operand2) + string(operand1)
            stack.push(temp)

        } else {
            stack.push(string(character))
        }
    }

    fmt.Print(stack)

}

func main() {
    input()
}

func input() {
    var stack Stack
    fmt.Print("Please input the equation without spaces: \n")
    input := "ABC/-AK/L-*"


    for _, character := range input {
        valueCheck := isOperator(string(character))
        if valueCheck {
            operand1 := stack[len(stack)-1]
            stack.pop()
            operand2 := stack[len(stack)-1]
            stack.pop()


            temp := string(character) + string(operand2) + string(operand1)
            stack.push(temp)

        } else {
            stack.push(string(character))
        }
    }

这将完全满足您的期望。

几个旁注:

  1. if valueCheck == true太多了,因为valueCheck是boolean类型
var temp string
temp = string(character) + string(operand2) + string(operand1)

也有点冗长

temp := string(character) + string(operand2) + string(operand1)

够了。

并且最好熟悉 dlv 调试器,这将在您下次不知所措时节省一些时间和精力。