4.7-逆波兰计算(后缀表达式):完成一个逆波兰计算器,分析和代码实现
要求完成以下任务
输入一个逆波兰表达式(后缀表达式),使用栈,计算其结果 支持小括号和多位整数 思路分析 代码完成
package com. hejiale. stack. v4 ;
import java. util. ArrayList ;
import java. util. List ;
import java. util. Stack ;
public class PolandNotation {
public static void main ( String [ ] args) {
String suffixExpression = "30 4 + 5 * 6 - " ;
List < String > listString = getListString ( suffixExpression) ;
int count = count ( listString) ;
System . out. println ( count) ;
}
public static List < String > getListString ( String suffixExpression) {
String [ ] s = suffixExpression. split ( " " ) ;
List < String > list = new ArrayList < String > ( ) ;
for ( String s1 : s) {
list. add ( s1) ;
}
return list;
}
public static int count ( List < String > list) {
Stack < String > stack = new Stack < > ( ) ;
for ( String item : list) {
if ( item. matches ( "\\d+" ) ) {
stack. push ( item) ;
} else {
int num2 = Integer . parseInt ( stack. pop ( ) ) ;
int num1 = Integer . parseInt ( stack. pop ( ) ) ;
int res = 0 ;
if ( item. equals ( "+" ) ) {
res = num1 + num2;
} else if ( item. equals ( "-" ) ) {
res = num1 - num2;
} else if ( item. equals ( "*" ) ) {
res = num1 * num2;
} else if ( item. equals ( "/" ) ) {
res = num1 / num2;
} else {
throw new RuntimeException ( "逆波兰表达式不正确" ) ;
}
stack. push ( res + "" ) ;
}
}
return Integer . parseInt ( stack. pop ( ) ) ;
}
}