# Convert infix notation to reverse polish notation (Java)

How to implement a calculator is a popular interview question. To answer this question well, you need to maser Stack data structures, convert an infix notation to RPN and evaluate reverse polish notation.

Since the input is usually in infix notation, e.g. “3 + 6 * 2”, it is difficult develop a program to evaluate it directly.

In practice, we can implement a calculator algorithm into two steps:

- the first step is to convert your mathematical expressions, which is called infix notation, into Reverse Polish Notation (RPN), or postfix notation.
- The second step to evaluate the RPN using a Stack based algorithm.

## What are Infix notation and Reverse polish Notation

### Infix notation

Infix notation is the common arithmetic and logical formula notation, which are used by us every day. For example (2 + 6 * 4) / (3 + 8) is a typical infix notation.

Although infix notation is natural for us, it is more difficult to parse by computers than prefix notation ( e.g. **+** 2 2 ) or postfix notation ( e.g. 2 2 **+** ).

### Reverse polish Notation

Reverse polish Notation (RPN), also known as **postfix notation,** is mathematical notation in which every operator (eg. + – * %) follows all of its operands.

The benefits of RPN is that it does not need any parentheses as long as each operator has a fixed number of operands.

For the infix expression `5 - 2`

, the corresponding RPN is `5 2 -`

.

The following table compares Infix notation and RPN using different examples:

Infix notationReverse Polish NotationA – B A B – A ^ 2 + 3 * A * B + B ^ 4 A 2 ^ 3 A * B * + B 4 ^ + ( ( 1 + 3 ) / 4 ) ^ 5 1 3 + 4 / 5 ^ ( 1 + 2 ) * ( 3 / 4 ) ^ ( a + b ) 1 2 + 3 4 / a b + ^ *

## Convert Infix notation to RPN

The most famous algorithm to convert infix notation to RPN is the shunting-yard algorithm. The algorithm was invented by Edsger Dijkstra and named the “shunting yard” algorithm because its operation resembles that of a railroad shunting yard.

Similar to the evaluation of RPN, the shunting yard algorithm is also stack based. We define two data variables:

- A queue
`Q`

to hold the final reverse polish notation. - A stack
`S`

to hold the operators that not added to the output queue.

In the convert process, we scan the tokens in the infix notation,

- If the current token is a number, we put it into the queue
- If the current token is an operator, we will do some rule check to determine when to put in to the stack.

The rules are based on the **operator precedence, **and** **whether it is a left associative or right associate operator.

Given an infix expression like `"2 + 6 * ( 3 - 4)",`

the resulted RPN is `"2 6 3 4 - * +"`

. Once we get the RPN, we can easily develop a program to evaluate this postfix notation.

## Pseudo code of the shunting-yard algorithm

Suppose we build a operator that only supports `+, -, *, /, (, ),`

we can first define precedence for each of the operator as following.

1 2 3 4 5 6 |
Map<String, Integer> prededence = new HashMap<>(); prededence.put("/", 5); prededence.put("*", 5); prededence.put("+", 4); prededence.put("-", 4); prededence.put("(", 0); |

A simplified shunting-yard algorithm likes this:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
Input: I is the infix notation. Q = [] S = [] For each token in I: if current_token: is a number: add it to output Q is '(' : Push it on to stack is ')' :{ Pop items off stack to output Q until '(' reached and delete the '(' from the stack S. } is an 'operator': { while s.notEmpty() && precedence(s.peek()) >= precedence(current_token){ Pop Stack to output Q } push current token to Stack S } After for loop: Finally pop all the elements in Stack S to output Q. |

Here are the **import rules** of the algorithm:

- When read
`a number`

, it is immediately added to the output queue`Q`

. - When read an
`'(',`

it is immediately added to the operator stack`S`

. - when read an ‘
`)`

‘, keep popping S until get ‘`(`

‘, and add all the popped operators to`Q`

. - At the end of reading, pop all operators off the stack and put them into the
`Q`

. - when read an operator, we need to check its precedence with the operator in the top of the stack.

## A simple explanation of the shunting-yard algorithm

We use a simple example to walk through the shunting-yard algorithm:

**Input: I = “2 + 6 * ( 3 – 4)”**

Define a queue `Q`

to record the final RPN.

Define a stack `S`

to hold the operators.

- Read
`2`

from the infix expression, as`2`

is a number, put it into Q. now`Q = [2]`

- Read
`+`

from the infix expression, put it into the stack S, now`S = [+]`

- Read
`6`

, as it is a number, put it into Q, now`Q = [ 2, 6]`

- Read
`*`

, as it is a operator, its left associative, and its precedence is larger than the top of S, put it into S, now`S = [* , +]`

. - Read
`(`

, simply put it into the stack. now`S = [ (, * , + ]`

- Read
`3`

, put it into Q, now`Q = [ 2, 6, 3]`

- Read
`-`

, the precedence of`'-'`

is always higher than ‘`)`

‘, put ‘`-`

‘ to S, now`S = [ -, (, *, +]`

- Read
`4`

, put it into Q, now`Q = [2, 6, 3, 4]`

- Read
`),`

now we do pop from S until we get ‘`(`

‘ , all the popped the operators are added to Q.12345while (S.peek() != '(' ) {o = S.pop()Q.add(o)}S.pop() // remove the '(' from the stack. - Now
`Q = [2, 6, 3, 4, -], S = [* , +]`

- At the end, we keep popping S, and put the elements to Q.
12345while (!S.isEmpty()) {Q.add(S.pop())}
- Now
`Q = [2, 6, 3, 4, -, *, +]`

, and`S = [].`

We print Q into a String to get the RPN: “`2 6 3 4 - * +`

“

**The implementation of the **shunting-yard algorithm in **Java**

The following code shows how to convert infix notation to RPN in Java. To make the program works in practice, it needs to do validation check, which is skipped here.

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 66 67 68 |
public class ConvertInfixToRPN { static boolean isNumber(String str) { try{ Double.valueOf(str); return true; } catch(Exception e){ return false; } } Queue<String> convertInfixToRPN(String[] infixNotation) { Map<String, Integer> prededence = new HashMap<>(); prededence.put("/", 5); prededence.put("*", 5); prededence.put("+", 4); prededence.put("-", 4); prededence.put("(", 0); Queue<String> Q = new LinkedList<>(); Stack<String> S = new Stack<>(); for (String token : infixNotation) { if ("(".equals(token)) { S.push(token); continue; } if (")".equals(token)) { while (!"(".equals(S.peek())) { Q.add(S.pop()); } S.pop(); continue; } // an operator if (prededence.containsKey(token)) { while (!S.empty() && prededence.get(token) <= prededence.get(S.peek())) { Q.add(S.pop()); } S.push(token); continue; } if (isNumber(token)) { Q.add(token); continue; } throw new IllegalArgumentException("Invalid input"); } // at the end, pop all the elements in S to Q while (!S.isEmpty()) { Q.add(S.pop()); } return Q; } public static void main(String[] args) { String[] infixNotation = {"33", "+", "23"}; System.out.println(new ConvertInfixToRPN().convertInfixToRPN(infixNotation)); String[] infixNotation2 = {"2", "*", "(", "3", "+", "4", "/", "2", ")"}; System.out.println(new ConvertInfixToRPN().convertInfixToRPN(infixNotation2)); } } |

The output:

1 2 |
[33, 23, +] [2, 3, 4, 2, /, +, *] |