Evaluation of postfix expression
Evaluation of postfix expression
================================================================================
- Postfix notation (also known as Reverse Polish Notation) is a way to represent an expression, where operators follow their corresponding operands.
- Evaluating an expression represented as postfix notation can easily be done using the stack data structure.
- Algorithm:
- begin
- x = read first symbol from postfix expression
- while(x)
- if (x is an operator)
- operand1: pop()
- operand2: pop()
- result = operand2 operator operand1
- push(result)
- end if
- else
- push(x)
- end else
- x = read next symbol
- end while
- end
- begin
- x = read first symbol from postfix expression
- while(x)
- if (x is an operator)
- operand1: pop()
- operand2: pop()
- result = operand2 operator operand1
- push(result)
- end if
- else
- push(x)
- end else
- x = read next symbol
- end while
- end
- eg.
- 6 2 3 + -
- Solution:
Symbol
Stack
Evaluation
6
2
3
+
operand1 = 3,
operand2 = 2
result = 2 +
3
-
operand1 = 5,
operand2 = 6
result = 6 -
5
- 6 2 3 + -
- Solution:
Symbol
Stack
Evaluation
6
2
3
+
operand1 = 3, operand2 = 2
result = 2 + 3
-
operand1 = 5, operand2 = 6
result = 6 - 5
Comments
Post a Comment