forked from spring1843/go-dsa
-
Notifications
You must be signed in to change notification settings - Fork 0
/
evaluate_postfix.go
65 lines (57 loc) · 1.33 KB
/
evaluate_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
62
63
64
65
package stack
import (
"fmt"
"strconv"
)
// EvaluatePostfixExpression solves the problem in O(n) time and O(n) space.
func EvaluatePostfixExpression(expression []string) (float64, error) {
stack := new(evaluation)
for _, element := range expression {
if _, ok := operands[element]; !ok {
if err := stack.pushString(element); err != nil {
return -1, err
}
continue
}
op2, err := stack.pop()
if err != nil {
return -1, err
}
op1, err := stack.pop()
if err != nil {
return -1, err
}
var result float64
switch element {
case "+":
result = op1 + op2
case "-":
result = op1 - op2
case "*":
result = op1 * op2
case "/":
result = op1 / op2
}
stack.push(result)
}
return stack.stack[len(stack.stack)-1], nil
}
func (evaluation *evaluation) pop() (float64, error) {
if len(evaluation.stack) == 0 {
return -1, ErrEmptyStack
}
tmp := evaluation.stack[len(evaluation.stack)-1]
evaluation.stack = evaluation.stack[:len(evaluation.stack)-1]
return tmp, nil
}
func (evaluation *evaluation) pushString(operand string) error {
f, err := strconv.ParseFloat(operand, 64)
if err != nil {
return fmt.Errorf("failed converting from float to string, %s", err)
}
evaluation.push(f)
return nil
}
func (evaluation *evaluation) push(f float64) {
evaluation.stack = append(evaluation.stack, f)
}