-
Notifications
You must be signed in to change notification settings - Fork 133
/
Copy pathinfix_to_postfix.go
61 lines (50 loc) · 1.2 KB
/
infix_to_postfix.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
package stack
const (
openParenthesis = "("
closeParenthesis = ")"
)
var operands = map[string]int{
"*": 1,
"/": 2,
"+": 3,
"-": 4,
}
type operators struct {
stack []string
}
// InfixToPostfix solves the problem in O(n) time and O(n) space.
func InfixToPostfix(infix []string) []string {
output := []string{}
stack := new(operators)
for _, element := range infix {
if _, ok := operands[element]; !ok && element != openParenthesis && element != closeParenthesis {
output = append(output, element)
continue
}
if element == closeParenthesis {
popped := stack.pop()
for popped != openParenthesis {
output = append(output, popped)
popped = stack.pop()
}
continue
}
if len(stack.stack) > 0 && operands[element] > operands[stack.stack[len(stack.stack)-1]] {
stack.push(element)
continue
}
stack.push(element)
}
for len(stack.stack) > 0 {
output = append(output, stack.pop())
}
return output
}
func (operators *operators) pop() string {
tmp := operators.stack[len(operators.stack)-1]
operators.stack = operators.stack[:len(operators.stack)-1]
return tmp
}
func (operators *operators) push(operator string) {
operators.stack = append(operators.stack, operator)
}