-
Notifications
You must be signed in to change notification settings - Fork 3
/
notation.go
119 lines (106 loc) · 2.05 KB
/
notation.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
package stack
import (
"fmt"
"strconv"
)
var priority = map[string]int{
"(": 1, ")": 1,
"*": 3, "/": 3,
"+": 4, "-": 4,
}
func isNum(s string) bool {
if _, err := strconv.ParseFloat(s, 64); err != nil {
return false
}
return true
}
func isOperator(s string) bool {
if s == "+" || s == "-" || s == "*" || s == "/" {
return true
}
return false
}
func isBracket(s string) bool {
if s == "(" || s == ")" {
return true
}
return false
}
func IN2PN(infix []string) (polish []string) {
s1, s2 := Constructor(), Constructor()
for i := len(infix) - 1; i >= 0; i-- {
s := infix[i]
if isNum(s) {
s2.Push(s)
} else if isOperator(s) {
if s1.IsEmpty() || s1.Top().(string) == ")" ||
priority[s] <= priority[s1.Top().(string)] {
s1.Push(s)
} else {
s2.Push(s1.Pop())
i++
}
} else if isBracket(s) {
if s == ")" {
s1.Push(s)
} else {
for !s1.IsEmpty() && s1.Top().(string) != ")" {
s2.Push(s1.Pop())
}
if s1.Top().(string) == ")" {
s1.Pop()
}
}
} else {
panic(fmt.Sprintf("error input: %s", s))
}
}
for !s1.IsEmpty() {
s2.Push(s1.Pop())
}
res, index := make([]string, s2.Len(), s2.Len()), 0
for !s2.IsEmpty() {
res[index] = s2.Pop().(string)
index++
}
return res
}
func IN2RPN(infix []string) (reversePolish []string) {
s1, s2 := Constructor(), Constructor()
for i := 0; i < len(infix); i++ {
s := infix[i]
if isNum(s) {
s2.Push(s)
} else if isOperator(s) {
if s1.IsEmpty() || s1.Top().(string) == "(" ||
priority[s] < priority[s1.Top().(string)] {
s1.Push(s)
} else {
s2.Push(s1.Pop())
i--
}
} else if isBracket(s) {
if s == "(" {
s1.Push(s)
} else {
for !s1.IsEmpty() && s1.Top().(string) != "(" {
s2.Push(s1.Pop())
}
if s1.Top().(string) == "(" {
s1.Pop()
}
}
} else {
panic(fmt.Sprintf("error input: %s", s))
}
}
for !s1.IsEmpty() {
s2.Push(s1.Pop())
}
res, index := make([]string, s2.Len(), s2.Len()), s2.Len()-1
for !s2.IsEmpty() {
res[index] = s2.Pop().(string)
index--
}
return res
}