Jes2ica.IO

coding, trading, reading

  1. 1. Evaluate a postfix expression
  2. 2. Evaluate a infix expression
  3. 3. Reference

Evaluate a postfix expression

Postfix expression: Operand1 Operand2 op

1
2
3
4
5
6
7
8
9
10
11
12
While (we have not reached the end of s)
If an operand is found
Push it onto the stack
End-If
If an operator is found
Pop the stack and call the value B
Pop the stack and call the value A
Evaluate A op B using the operator just found
Push the result onto the stack
End-If
End-While
Pop the stack (this is the final value)

Evaluate a infix expression

Infix expression: Operand1 op Operand2

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
Stacks: ops, values
While (we have not reached the end of s)
If an operand is found
Push it onto the stack: values
End-If
If a left parenthesis is found
Push it onto the stack: ops
End-If
If a right parenthesis is found
While (the stack: ops is not empty AND the top item is not a left parenthesis)
Pop the stack: ops and add the popped value to stack: values
End-If
If an operator is found
While (the stack is not empty AND the top of the stack is not a left parenthesis AND precedence of the operator <= precedence of the top of the stack)
Pop the stack: ops and add the top value to stack: values
End-While
Push the latest operator onto the stack: ops
End-If
End-While

While (the stack is not empty)
Pop the stack and add the popped value to stack: values;
End-While
Pop the stack (this is the final value)

Reference

This article was last updated on days ago, and the information described in the article may have changed.