功能介绍
表达式可以包含+
,-
,*
,/
,(
,)
五种运算符。
若表达式输入错误,则提示错误信息;若表达式无误,则输出正确结果。
例如输入43-40*2-(80-3)
,输出结果-114
注意:允许输入多组()
嵌套,只要合法即可,如(43-40)*(2-(8+3))
,属于合法表达式。
实现思路
采用两个栈来实现表达式的计算:(自己实现一个栈)
- 数字栈:用来存储表达式中的操作数
- 符号栈:用来存储表达式中的运算符号
定义每个符号的优先级,根据优先级顺序来确定什么时候符号存,什么时候取出来运算。
采用一个个遍历运算字符串的字符来进行运算,需要注意两个问题:
- 数字不只是个位数,可能有多位数,因此需要注意判断合并。
-
号的处理采用将下一个数字取相反数,然后符号存入+
号,为了避免当出现如-3-5
时,由于两个-
号的优先级相同,先计算3-5
,然后结果就是-(-2)=2
了。- 遍历字符串的时候,每个字符的类型为
int32
,在测试的时候发现int32
对应的数字与实际字符串的数字不一致,因此需要编写一个方法Int32ToInt
(具体实现代码如下),实现两种类型的转换。
栈的定义代码
/**
* @Author: lena
* @Date: 2021/9/23 16:32
* @Description: 用数组实现栈
* @Version: 1.0.0
*/
package data_structure
type Stack struct {
size int // 栈能存储的容量
top int // 栈顶
data []interface{
} // 栈内元素
}
// 创建栈
func NewStack(size int) *Stack {
return &Stack{
size: size,
top: 0,
data: make([]interface{
},size),
}
}
// 栈满
func (this *Stack)IsFull() bool {
// 当top=数组最大长度,说明栈满
return this.top == this.size
}
//栈空
func (this *Stack)IsEmpty() bool {
return this.top == 0
}
// 出栈
func (this *Stack)Pop() (interface{
},bool) {
// 栈空
if this.IsEmpty() {
return 0,false
}
// 栈顶指针向下移动
this.top--
//fmt.Println("出栈:",this.data[this.top])
return this.data[this.top],true
}
// 入栈
func (this *Stack)Push(d interface{
}) bool {
// 栈满
if this.IsFull() {
return false
}
this.data[this.top]=d
this.top++
//fmt.Println("入栈:",d)
return true
}
// 获取栈顶元素但不出栈
func (this *Stack)Peek() (interface{
},bool) {
// 栈空
if this.IsEmpty() {
return 0,false
}
return this.data[this.top-1],true
}
// 栈内元素
func (this *Stack)Len() int {
return this.top
}
栈的测试代码
/**
* @Author: lena
* @Date: 2021/9/23 21:53
* @Description: stack_test.go
* @Version: 1.0.0
*/
package data_structure
import (
"reflect"
"testing"
)
func TestStack(t *testing.T) {
stack:= NewStack(3)
if !reflect.DeepEqual(stack.IsEmpty(),true) {
t.Errorf("error")
}
stack.Push("zh")
stack.Push("-")
if !reflect.DeepEqual(stack.IsEmpty(),false) {
t.Errorf("error")
}
if !reflect.DeepEqual(stack.IsFull(),false) {
t.Errorf("error")
}
stack.Push("ku")
if !reflect.DeepEqual(stack.Len