# Evaluation of inverse Polish expression for stack and queue algorithm problems

catalogue

Inverse Polish expression evaluation

describe

explain

Example   one

Example   two

Example   three

Tips

Reverse Polish notation

Method: stack

Method 2: array simulation stack

# Inverse Polish expression evaluation

## describe

Find the value of the expression according to the inverse Polish representation.

Valid operators include  +,-,*,/ . Each operand can be an integer or another inverse expression.

## explain

Integer division preserves only the integer part.
The given inverse Polish expression is always valid. In other words, an expression always yields a valid value and there is no case where the divisor is 0.

## Example   one

```Input: tokens = ["2","1","+","3","*"]
Output: 9
Explanation: this expression is transformed into a common infix arithmetic expression:((2 + 1) * 3) = 9```

## Example   two

```Input: tokens = ["4","13","5","/","+"]
Output: 6
Explanation: this expression is transformed into a common infix arithmetic expression:(4 + (13 / 5)) = 6```

## Example   three

```Input: tokens = ["10","6","9","3","+","-11","*","/","*","17","+","5","+"]
Output: 22
Explanation:
This expression is transformed into a common infix arithmetic expression as follows:
((10 * (6 / ((9 + 3) * -11))) + 17) + 5
= ((10 * (6 / (12 * -11))) + 17) + 5
= ((10 * (6 / -132)) + 17) + 5
= ((10 * 0) + 17) + 5
= (0 + 17) + 5
= 17 + 5
= 22```

## Tips

• tokens[i] is either an operator ("+", "-", "*" or "/") or an integer in the range [- 200, 200]

## Reverse Polish notation

Inverse Polish expression is a suffix expression. The so-called suffix means that the operator is written after it.

The commonly used formula is an infix expression, such as (1 + 2) * (3 + 4).
The inverse Polish expression of the formula is written as ((1,2 +) (3,4 +) *).
The inverse Polish expression has the following two advantages:

After removing the brackets, the expression is unambiguous. Even if the above formula is written as 1 2 + 3 4 + *, the correct result can be calculated according to the order.
Suitable for stack operation: enter the stack when encountering numbers; In case of an operator, take out the two numbers at the top of the stack for calculation, and press the result into the stack.

## Method: stack

In fact, the topic has already said the idea of solving the problem. This topic is suitable for stack operation.

If a number is encountered, it will be put on the stack; In case of an operator, take out the two numbers at the top of the stack for calculation, and press the result into the stack.

We use regular expressions to determine whether the current character is a number.

```import java.util.regex.Pattern;

class Solution {
public int evalRPN(String[] tokens) {
Stack<String> stack=new Stack<>();
int n1,n2;
for (int i = 0; i < tokens.length; i++) {
if (isNumber(tokens[i])){//If number
stack.push(tokens[i]);//Push
}else{//If it is an operation symbol
n2=Integer.parseInt(stack.pop());//Operand 2
n1=Integer.parseInt(stack.pop());//Operand 1
if ("+".equals(tokens[i])) stack.push(n1+n2+"");//Writes the result back to the stack
else if ("-".equals(tokens[i])) stack.push(n1-n2+"");//Writes the result back to the stack
else if ("*".equals(tokens[i])) stack.push(n1*n2+"");//Writes the result back to the stack
else if ("/".equals(tokens[i])) stack.push(n1/n2+"");//Writes the result back to the stack
}
}
return Integer.parseInt(stack.pop());//Return final result
}

public boolean isNumber(String string) {//Regular expression determines whether it is a number
if (string == null)
return false;
Pattern isNumber = Pattern.compile("^-?\\d+(\\.\\d+)?\$");
return isNumber.matcher(string).matches();
}
}```

## Method 2: array simulation stack

For a valid inverse Polish expression, its length n must be odd, and there must be one more operand than the operator (that is, the number of operands is (n+1)/2, and the operator is (n-1)/2)

We define an array stack with a length of (n+1)/2 to simulate the stack, and define an index variable to indicate the position of the top element of the stack (initialized to - 1). When operands and operators are encountered:

• Operand: move index to the right, and assign the operand to stack[index], that is, stack[++index]=tokens[i]
• Operator: shift index to the left, operate the left operand stack[index] and the right operand stack[index+1], and assign the result to stack[index] (for example, stack[--index]=stack[index]+stack[index+1])
```class Solution {
public int evalRPN(String[] tokens) {
int[] stack=new int[(tokens.length+1)/2];
int index=-1;//Point to stack top element
for (int i = 0; i < tokens.length; i++) {
String token=tokens[i];
switch (token){
case "+"://If it is an operator, the calculation results coexist back to the array
stack[--index]=stack[index]+stack[index+1];
break;
case "-":
stack[--index]=stack[index]-stack[index+1];
break;
case "*":
stack[--index]=stack[index]*stack[index+1];
break;
case "/":
stack[--index]=stack[index]/stack[index+1];
break;
default://If it is a number, it is stacked
stack[++index]=Integer.parseInt(token);
}
}
return stack[index];
}
}```

Tags: stack array

Posted on Wed, 27 Oct 2021 21:37:31 -0400 by werlop
{"found_math": false, "script_math_tex": 0, "script_math_asciimath": 0, "math_annotations": 0, "math_alttext": 0, "mathml": 0, "mathjax_tag": 0, "mathjax_inline_tex": 0, "mathjax_display_tex": 0, "mathjax_asciimath": 0, "img_math": 0, "codecogs_latex": 0, "wp_latex": 0, "mimetex.cgi": 0, "/images/math/codecogs": 0, "mathtex.cgi": 0, "katex": 0, "math-container": 0, "wp-katex-eq": 0, "align": 0, "equation": 0, "x-ck12": 0, "texerror": 0}