-
Notifications
You must be signed in to change notification settings - Fork 0
/
polish.go
73 lines (65 loc) · 1.13 KB
/
polish.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
package main
import (
"fmt"
"os"
"strings"
"bufio"
)
type Stack []int
func (st *Stack) isEmpty() bool {
return len(*st) == 0
}
func (st *Stack) push(data int) {
*st = append(*st, data)
}
func (st *Stack) pop() bool {
if st.isEmpty() {
return false
} else {
index := len(*st) - 1
*st = (*st)[:index]
return true
}
}
func (st *Stack) top() int {
if st.isEmpty() {
return -1
} else {
return (*st)[len(*st)-1]
}
}
func polish(s string) {
st := Stack{}
for i := len(s) - 1; i >= 0; i-- {
if s[i] == ' ' || s[i] == '(' || s[i] == ')' {
continue
} else if s[i] >= '0' && s[i] <= '9' {
st.push(int(s[i]) - '0')
} else {
op := s[i]
a := st.top()
st.pop()
b := st.top()
st.pop()
switch op {
case '+':
st.push(a + b)
case '-':
st.push(a - b)
case '*':
st.push(a * b)
}
}
}
if len(st) == 1 {
fmt.Println(st.top())
} else {
fmt.Println("uncorrect expression")
}
}
func main() {
reader := bufio.NewReader(os.Stdin)
text, _ := reader.ReadString('\n')
text = strings.Trim(text, " \n")
polish(text)
}