This program demonstrates how to evaluate a postfix expression using a stack in Go. Postfix expressions are advantageous in computational contexts because they remove the need for parentheses to dictate the order of operations, allowing for straightforward machine parsing and evaluation.
Program Code
package main
import (
"fmt"
"strconv"
"strings"
)
// Stack type using a slice for storage
type Stack struct {
elements []int
}
// Push adds an element to the stack
func (s *Stack) Push(value int) {
s.elements = append(s.elements, value)
}
// Pop removes the top element from the stack and returns it
func (s *Stack) Pop() int {
if len(s.elements) == 0 {
panic("pop from empty stack")
}
lastIndex := len(s.elements) - 1
top := s.elements[lastIndex]
s.elements = s.elements[:lastIndex]
return top
}
// EvaluatePostfix evaluates a given postfix expression string
func EvaluatePostfix(expression string) int {
var s Stack
tokens := strings.Fields(expression)
for _, token := range tokens {
switch token {
case "+", "-", "*", "/":
right := s.Pop()
left := s.Pop()
switch token {
case "+":
s.Push(left + right)
case "-":
s.Push(left - right)
case "*":
s.Push(left * right)
case "/":
s.Push(left / right)
}
default:
value, err := strconv.Atoi(token)
if err != nil {
panic("invalid token")
}
s.Push(value)
}
}
return s.Pop()
}
func main() {
expression := "3 4 2 * 1 5 - 2 3 ^ ^ / +"
fmt.Println("Postfix Expression:", expression)
result := EvaluatePostfix(expression)
fmt.Println("Evaluated Result:", result)
}
Explanation
- Stack Operations: The program defines a simple stack type that supports
Push
andPop
operations to manage integers, facilitating the evaluation process. - Evaluating the Postfix Expression: The function
EvaluatePostfix
parses and evaluates the expression:- Numerical tokens are directly pushed onto the stack.
- When an operator is encountered, the appropriate number of operands (two for binary operators) are popped from the stack, the operation is performed, and the result is pushed back onto the stack.
- Result Retrieval: At the end of the expression, the stack should contain only one element, the result of the expression, which is returned by the final
Pop
.
Running the Program
To execute this program:
- Save the code in a file named
evaluatepostfix.go
. - Open a terminal or command prompt.
- Navigate to the directory containing your file.
- Type
go run evaluatepostfix.go
to run the program.
The output will display the original postfix expression and its evaluated result, demonstrating how the stack is used to perform the calculation step-by-step.