一.中缀表达式
1.1计算思路
数入左,运入右
栈空直接入,不空看优先
大于等于则出栈,否则都入栈
左括直接入,遇右吐出来
- 数入左,运入右,栈空直接入
- 不空看优先,栈顶元素为+,优先级小于扫描元素*的优先级,直接入栈
- 数直接入左栈
- 不空看优先,栈顶元素为*,优先级等于扫描元素的优先级,出栈运算,结果入左栈
将左栈 3 取出,放左边,右栈 取出放中间,再取左栈7,放右边,运算结果入左栈
之后将 与此时栈顶元素+比,栈顶元素优先级小于 * ,直接入栈
- 左括直接入
- 遇 ),( 之后的都要出栈运算
- 最后依次出栈运算
1.2代码实现(运算只包含加减乘除,无括号)
之前的栈要扩展一些功能
- 判断运算符的优先级,使用数字表示,数字越大,优先级越高
//运算符+ - * / 的优先级
public int priority(int oper){
if (oper=='*'||oper=='/'){
return 1;
}else if (oper=='+'||oper=='-'){
return 0;
}else {
throw new RuntimeException("运算符错误");
}
}
- 判断是否是个运算符
//判断扫描到的是否是运算符
public boolean isOper(char val) {
return val == '+' || val == '-' || val == '*' || val == '/';
}
- 出栈数据进行运算
//出栈数据计算
public int cal(int num1, int num2, int oper) {
int result = 0;
switch (oper) {
case '+':
result = num1 + num2;
break;
case '-':
result = num2 - num1;
break;
case '*':
result = num1 * num2;
break;
case '/':
result = num2 / num1;
break;
}
return result;
}
- 返回栈顶的值,但不出栈
在这里插入代码片
代码实现:
- 栈类
package Stack;
public class ArrayStack {
private int[] stack;
private int top = -1;
private int maxsize;
public ArrayStack(int maxsize) {
this.maxsize = maxsize;
//数组初始化
stack = new int[this.maxsize];
}
//判断栈满
public boolean isFull() {
return top == maxsize - 1;
}
//判断栈空
public boolean isEmpty() {
return top == -1;
}
//入栈
public void push(int n) {
if (isFull()) {
System.out.println("栈满");
return;
} else {
top++;
stack[top] = n;
}
}
//出栈
public int pop() {
if (isEmpty()) {
throw new RuntimeException("栈空");
} else {
int value = stack[top];
top--;
return value;
}
}
//显示栈内数据
public void show() {
if (isEmpty()) {
System.out.println("栈空");
} else {
for (int i = top; i >= 0; i--) {
System.out.println(stack[i]);
}
}
}
//运算符+ - * / 的优先级
public int priority(int oper) {
if (oper == '*' || oper == '/') {
return 1;
} else if (oper == '+' || oper == '-') {
return 0;
} else {
throw new RuntimeException("运算符错误");
}
}
//判断扫描到的是否是运算符
public boolean isOper(char val) {
return val == '+' || val == '-' || val == '*' || val == '/';
}
//出栈数据计算
public int cal(int num1, int num2, int oper) {
int result = 0;
switch (oper) {
case '+':
result = num1 + num2;
break;
case '-':
result = num2 - num1;
break;
case '*':
result = num1 * num2;
break;
case '/':
result = num2 / num1;
break;
}
return result;
}
//返回栈顶的值,但不出栈
public int showTop(){
return stack[top];
}
}
- 主程序
package Stack;
public class DemoInfixExpression {
public static void main(String[] args) {
//表达式
String infixExpression = "31+2*6-2";
//创建两个栈,一个数栈,一个符号栈
ArrayStack numStack = new ArrayStack(10);
ArrayStack operStack = new ArrayStack(10);
//定义一个扫描表达式的指针
int index = 0;
//定义弹出栈的两个数和运算符
int num1=0;
int num2=0;
int oper=0;
//定义弹出栈的两个数的运算结果
int res = 0;
//将每次扫描到infixExpression表达式的char保存到ch
char ch =' ';
String keepnum="";//用于拼接多位数
//while循环扫描infixExpression
while (true){
//依次得到infixExpression中的每个字符
//字符串名.substring(int a,int b);
// 截取从第a号索引位置开始到第b号索引位置(不包括b),[a,b)
//.charAt(0)字符串转字符
ch = infixExpression.substring(index,index+1).charAt(0);
//判断ch是什么,然后做相应的处理
if (operStack.isOper(ch)){//如果是运算符
//判断符号栈是否为空
//如果为空,直接入栈
//如果入栈的符号优先级小于栈顶符号优先级,直接入栈
if (operStack.isEmpty()||operStack.priority(ch)>operStack.priority(operStack.showTop())){
operStack.push(ch);
}else{//如果入栈的符号优先级大于等于栈顶符号优先级,数栈和符号栈弹出数据运算
num1=numStack.pop();//数栈弹出数据1
num2=numStack.pop();//数栈接着弹出数据2
oper=operStack.pop();//符号栈弹出运算符
res=numStack.cal(num1,num2,oper);//栈外数据运算
numStack.push(res);//数据运算结果入数栈
operStack.push(ch);//当前运算符入符号栈
}
}else{//如果是数,直接入数栈
//numStack.push(ch-48);//字符'1'-48,转化为int 1
//当处理多位数时,不能发现是一个数,就入栈,可能是多位数
//处理:先造一个字符串接收数字,直到继续扫描index的下一位为运算符,或者最后expression最后一位,直接入栈
keepnum=keepnum+ch;//造一个字符串接收数字
//直到继续扫描index的下一位为运算符,入栈
// 或者最后expression最后一位,直接入栈
if (infixExpression.length()-1==index){
numStack.push(Integer.parseInt(keepnum));
}else if(numStack.isOper(infixExpression.substring(index+1,index+2).charAt(0))) {
numStack.push(Integer.parseInt(keepnum));
//keepnum使用完后记得清空
keepnum="";
}
}
index++;
if (index>=infixExpression.length()){
break;
}
}
//当表达式扫描完毕,就顺序的从数栈和符号栈中pop出相应的数和符号,并运行。
while (!operStack.isEmpty()){
num1=numStack.pop();
num2=numStack.pop();
oper=operStack.pop();
res=numStack.cal(num1,num2,oper);
numStack.push(res);
}
System.out.println(res);
}
}
二.前缀表达式(波兰式)
前缀表达式又称波兰式,前缀表达式的运算符位于操作数之前
举例说明: (3+4)×5-6 对应的前缀表达式就是 - × + 3 4 5 6
2.1计算思路
例如: (3+4)×5-6 对应的前缀表达式就是 - × + 3 4 5 6 , 针对前缀表达式求值步骤如下:
- 从右至左扫描,将6、5、4、3压入堆栈
- 遇到+运算符,因此弹出3和4(3为栈顶元素,4为次顶元素),计算出3+4的值,得7,再将7入栈
- 接下来是×运算符,因此弹出7和5,计算出7×5=35,将35入栈
- 最后是-运算符,计算出35-6的值,即29,由此得出最终结果
三.后缀表达式(逆波兰式)
后缀表达式又称逆波兰表达式,与前缀表达式相似,只是运算符位于操作数之后
举例说明: (3+4)×5-6 对应的后缀表达式就是 3 4 + 5 × 6 –
2.2计算思路
例如: (3+4)×5-6 对应的后缀表达式就是 3 4 + 5 × 6 - , 针对后缀表达式求值步骤如下:
- 从左至右扫描,将3和4压入堆栈;
- 遇到+运算符,因此弹出4和3(4为栈顶元素,3为次顶元素),计算出3+4的值,得7,再将7入栈;
- 将5入栈;
- 接下来是×运算符,因此弹出5和7,计算出7×5=35,将35入栈;
- 将6入栈;
- 最后是-运算符,计算出35-6的值,即29,由此得出最终结果
完成一个逆波兰计算器,要求完成如下任务:
- 输入一个逆波兰表达式(后缀表达式),使用栈(Stack), 计算其结果
- 支持小括号和多位数整数,因为这里主要讲的是数据结构,因此计算器进行简化,只支持对整数的计算。
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
import java.util.stream.Stream;
public class Demo01 {
public static void main(String[] args) {
//先定义逆波兰表达式
//(3+4)×5-6 = 3 4 + 5 × 6 -
String suffixExpression = "3 4 + 5 × 6 -";
//思路
//1.先将“3 4 + 5 × 6 -"=>放到ArrayList中
//2.将Arraylist传递给一个方法,遍历ArrayList 配合栈完成计算
List<String> list = getListString(suffixExpression);
int res = calculate(list);
System.out.println(res);
}
//先将“3 4 + 5 × 6 -"=>放到ArrayList中
public static List<String> getListString(String Expression) {
List<String> list = new ArrayList<>();
String[] strings = Expression.split(" ");
//使用Stream流静态方法,获取数组中每个数据,放入list中
Stream.of(strings).forEach(i -> list.add(i));
return list;
}
/**
* 计算思路:
* 1. 从左至右扫描,将3和4压入堆栈;
* 2. 遇到+运算符,因此弹出4和3(4为栈顶元素,3为次顶元素),计算出3+4的值,得7,再将7入栈;
* 3. 将5入栈;
* 4. 接下来是×运算符,因此弹出5和7,计算出7×5=35,将35入栈;
* 5. 将6入栈;
* 6. 最后是-运算符,计算出35-6的值,即29,由此得出最终结果
* */
public static int calculate(List<String> list){
Stack<String> stack = new Stack<>();
for (String i:list){
//这里使用正则表达式取出数
if (i.matches("\\d+")){//匹配的是数
//压入堆栈
stack.push(i);
}else {//遇到运算符,弹出4和3(4为栈顶元素,3为次顶元素),计算出3+4的值,得7,再将7入栈;
int num1 = Integer.parseInt(stack.pop());
int num2 = Integer.parseInt(stack.pop());
int result=0;
if (i.equals("+")){
result=num2+num1;
}else if (i.equals("-")){
result=num2-num1;
}else if (i.equals("×")){
result=num2*num1;
}else if (i.equals("/")){
result=num2/num1;
}else {
throw new RuntimeException("错误符号");
}
//将最后结果入栈
stack.push(result+"");
}
}
return Integer.parseInt(stack.pop());
}
}
2.3 中缀表达式转后缀表达式
- 初始化两个栈:运算符栈s1和储存中间结果的栈s2;
- 从左至右扫描中缀表达式;
- 遇到操作数时,将其压s2;
- 遇到运算符时,比较其与s1栈顶运算符的优先级:
1.如果s1为空,或栈顶运算符为左括号“(”,则直接将此运算符入栈;
2.否则,若优先级比栈顶运算符的高,也将运算符压入s1;
3.否则,将s1栈顶的运算符弹出并压入到s2中,再次转到(4.1)与s1中新的栈顶运算符相比较;- 遇到括号时:(1) 如果是左括号“(”,则直接压入s1 (2) 如果是右括号“)”,则依次弹出s1栈顶的运算符,并压入s2,直到遇到左括号为止,此时将这一对括号丢弃
- 重复步骤2至5,直到表达式的最右边
- 将s1中剩余的运算符依次弹出并压入s2
- 依次弹出s2中的元素并输出,结果的逆序即为中缀表达式对应的后缀表达式
public static List<String> toInfixExpressionList(String expression) {
//定义一个List
List<String> list = new ArrayList<String>();
//遍历字符串
int i = 0;
//对多位数的拼接
String str;
//每次遍历一个字符 就放到c中
char c;
do {
//如果是非数字
if ((c = expression.charAt(i)) < 48 || (c = expression.charAt(i)) > 57) {
list.add(String.valueOf(c));
i++;
} else {
//如果是一个数 需要考虑多位数
str = "";
while (i < expression.length() && (c = expression.charAt(i)) >= 48 && (c = expression.charAt(i)) <= 57) {
str = str + c;
i++;
}
list.add(str);
}
} while (i < expression.length());
return list;
}
public static List<String> parseList(List<String> list) {
//初始化栈
Stack<String> s1 = new Stack<>();
//因为s2没有pop操作 比较麻烦 此时使用 List操作
//Stack<String> s2 = new Stack<>();
List<String> s2 = new ArrayList<> ();
//遍历list
for (String ss : list){
//如果是一个数 入栈
if (ss.matches("\\d+")){
s2.add(ss);
}else if (ss.equals("(")){
s1.push(ss);
}else if (ss.equals(")")){
while (!s1.peek().equals("(")){
s2.add(s1.pop());
}
s1.pop();
}else {
//当s1栈
while (s1.size()!=0&&Operation.getValue(s1.peek()) >= Operation.getValue(ss)){
s2.add(s1.pop());
}
//还需要加入 ss 到栈
s1.push(ss);
}
}
while (s1.size()!=0){
s2.add(s1.pop());
}
return s2;
}
2.3 完整代码
package cn.icanci.datastructure.stack;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
/**
* @Author: icanci
* @ProjectName: AlgorithmAndDataStructure
* @PackageName: cn.icanci.datastructure.stack
* @Date: Created in 2020/3/2 19:52
* @ClassAction: 逆波兰表达式
*/
public class PolandNotation {
public static void main(String[] args) {
//1.(3+4)x5-6 => 3 4 + 5 * 6 -
//2.直接对str扫描 不方便 因此需要小转出 中缀的 list
String exptession = "1+((2+3)*4)-5";
List<String> toInfixExpr = toInfixExpressionList(exptession);
System.out.println(toInfixExpr);
List<String> suffixExpresion = parseList(toInfixExpr);
int val = calculate(suffixExpresion);
System.out.println(val);
}
//将中缀表达式占城为对应的List
public static List<String> toInfixExpressionList(String expression) {
//定义一个List
List<String> list = new ArrayList<String>();
//遍历字符串
int i = 0;
//对多位数的拼接
String str;
//每次遍历一个字符 就放到c中
char c;
do {
//如果是非数字
if ((c = expression.charAt(i)) < 48 || (c = expression.charAt(i)) > 57) {
list.add(String.valueOf(c));
i++;
} else {
//如果是一个数 需要考虑多位数
str = "";
while (i < expression.length() && (c = expression.charAt(i)) >= 48 && (c = expression.charAt(i)) <= 57) {
str = str + c;
i++;
}
list.add(str);
}
} while (i < expression.length());
return list;
}
public static List<String> parseList(List<String> list) {
//初始化栈
Stack<String> s1 = new Stack<>();
//因为s2没有pop操作 比较麻烦 此时使用 List操作
//Stack<String> s2 = new Stack<>();
List<String> s2 = new ArrayList<> ();
//遍历list
for (String ss : list){
//如果是一个数 入栈
if (ss.matches("\\d+")){
s2.add(ss);
}else if (ss.equals("(")){
s1.push(ss);
}else if (ss.equals(")")){
while (!s1.peek().equals("(")){
s2.add(s1.pop());
}
s1.pop();
}else {
//当s1栈
while (s1.size()!=0&&Operation.getValue(s1.peek()) >= Operation.getValue(ss)){
s2.add(s1.pop());
}
//还需要加入 ss 到栈
s1.push(ss);
}
}
while (s1.size()!=0){
s2.add(s1.pop());
}
return s2;
}
//将一个后缀 (逆波兰) 表达式 放在一个ArrayList中
public static List<String> getListString(String suffixExpresion) {
//将 suffixExpresion 分隔
String[] s = suffixExpresion.split(" ");
List<String> list = new ArrayList<String>();
for (String ele : s) {
list.add(ele);
}
return list;
}
//完成对逆波兰表达式的计算
public static int calculate(List<String> list) {
//创建栈 只需要一个栈
Stack<String> stack = new Stack<>();
//遍历
for (String ele : list) {
//使用正则表达式
if (ele.matches("\\d+")) {
//如果匹配的是数字
//入站
stack.push(ele);
} else {
int res = 0;
//pop 数运算
int num2 = Integer.parseInt(stack.pop());
int num1 = Integer.parseInt(stack.pop());
if (ele.equals("+")) {
res = num2 + num1;
} else if (ele.equals("-")) {
res = num1 - num2;
} else if (ele.equals("*")) {
res = num1 * num2;
} else if (ele.equals("/")) {
res = num1 / num2;
} else {
System.out.println("数据输入错误");
}
stack.push(res + "");
}
}
//返回最有一个
return Integer.parseInt(stack.pop());
}
}
//编写一个类
class Operation{
private static int ADD = 1;
private static int SUB = 1;
private static int MUL = 2;
private static int DIV = 2;
public static int getValue(String operation){
int result = 0;
switch (operation){
case "+":
result = ADD;
break;
case "-":
result = SUB;
break;
case "*":
result = MUL;
break;
case "/":
result = DIV;
break;
default:
System.out.println("找不到的元算符");
break;
}
return result;
}
}
逆波兰表达式计算器完整版
完整版的逆波兰计算器,功能包括
支持 + - * / ( )
多位数,支持小数,
兼容处理, 过滤任何空白字符,包括空格、制表符、换页符
package cn.icanci.datastructure.stack;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Stack;
import java.util.regex.Pattern;
/**
* @Author: icanci
* @ProjectName: AlgorithmAndDataStructure
* @PackageName: cn.icanci.datastructure.stack
* @Date: Created in 2020/3/2 21:55
* @ClassAction:
*/
public class ReversePolishMultiCalc {
/**
* 匹配 + - * / ( ) 运算符
*/
static final String SYMBOL = "\\+|-|\\*|/|\\(|\\)";
static final String LEFT = "(";
static final String RIGHT = ")";
static final String ADD = "+";
static final String MINUS= "-";
static final String TIMES = "*";
static final String DIVISION = "/";
/**
* 加減 + -
*/
static final int LEVEL_01 = 1;
/**
* 乘除 * /
*/
static final int LEVEL_02 = 2;
/**
* 括号
*/
static final int LEVEL_HIGH = Integer.MAX_VALUE;
static Stack<String> stack = new Stack<>();
static List<String> data = Collections.synchronizedList(new ArrayList<String>());
/**
* 去除所有空白符
* @param s
* @return
*/
public static String replaceAllBlank(String s ){
// \\s+ 匹配任何空白字符,包括空格、制表符、换页符等等, 等价于[ \f\n\r\t\v]
return s.replaceAll("\\s+","");
}
/**
* 判断是不是数字 int double long float
* @param s
* @return
*/
public static boolean isNumber(String s){
Pattern pattern = Pattern.compile("^[-\\+]?[.\\d]*$");
return pattern.matcher(s).matches();
}
/**
* 判断是不是运算符
* @param s
* @return
*/
public static boolean isSymbol(String s){
return s.matches(SYMBOL);
}
/**
* 匹配运算等级
* @param s
* @return
*/
public static int calcLevel(String s){
if("+".equals(s) || "-".equals(s)){
return LEVEL_01;
} else if("*".equals(s) || "/".equals(s)){
return LEVEL_02;
}
return LEVEL_HIGH;
}
/**
* 匹配
* @param s
* @throws Exception
*/
public static List<String> doMatch (String s) throws Exception{
if(s == null || "".equals(s.trim())) throw new RuntimeException("data is empty");
if(!isNumber(s.charAt(0)+"")) throw new RuntimeException("data illeagle,start not with a number");
s = replaceAllBlank(s);
String each;
int start = 0;
for (int i = 0; i < s.length(); i++) {
if(isSymbol(s.charAt(i)+"")){
each = s.charAt(i)+"";
//栈为空,(操作符,或者 操作符优先级大于栈顶优先级 && 操作符优先级不是( )的优先级 及是 ) 不能直接入栈
if(stack.isEmpty() || LEFT.equals(each)
|| ((calcLevel(each) > calcLevel(stack.peek())) && calcLevel(each) < LEVEL_HIGH)){
stack.push(each);
}else if( !stack.isEmpty() && calcLevel(each) <= calcLevel(stack.peek())){
//栈非空,操作符优先级小于等于栈顶优先级时出栈入列,直到栈为空,或者遇到了(,最后操作符入栈
while (!stack.isEmpty() && calcLevel(each) <= calcLevel(stack.peek()) ){
if(calcLevel(stack.peek()) == LEVEL_HIGH){
break;
}
data.add(stack.pop());
}
stack.push(each);
}else if(RIGHT.equals(each)){
// ) 操作符,依次出栈入列直到空栈或者遇到了第一个)操作符,此时)出栈
while (!stack.isEmpty() && LEVEL_HIGH >= calcLevel(stack.peek())){
if(LEVEL_HIGH == calcLevel(stack.peek())){
stack.pop();
break;
}
data.add(stack.pop());
}
}
start = i ; //前一个运算符的位置
}else if( i == s.length()-1 || isSymbol(s.charAt(i+1)+"") ){
each = start == 0 ? s.substring(start,i+1) : s.substring(start+1,i+1);
if(isNumber(each)) {
data.add(each);
continue;
}
throw new RuntimeException("data not match number");
}
}
//如果栈里还有元素,此时元素需要依次出栈入列,可以想象栈里剩下栈顶为/,栈底为+,应该依次出栈入列,可以直接翻转整个stack 添加到队列
Collections.reverse(stack);
data.addAll(new ArrayList<>(stack));
System.out.println(data);
return data;
}
/**
* 算出结果
* @param list
* @return
*/
public static Double doCalc(List<String> list){
Double d = 0d;
if(list == null || list.isEmpty()){
return null;
}
if (list.size() == 1){
System.out.println(list);
d = Double.valueOf(list.get(0));
return d;
}
ArrayList<String> list1 = new ArrayList<>();
for (int i = 0; i < list.size(); i++) {
list1.add(list.get(i));
if(isSymbol(list.get(i))){
Double d1 = doTheMath(list.get(i - 2), list.get(i - 1), list.get(i));
list1.remove(i);
list1.remove(i-1);
list1.set(i-2,d1+"");
list1.addAll(list.subList(i+1,list.size()));
break;
}
}
doCalc(list1);
return d;
}
/**
* 运算
* @param s1
* @param s2
* @param symbol
* @return
*/
public static Double doTheMath(String s1,String s2,String symbol){
Double result ;
switch (symbol){
case ADD : result = Double.valueOf(s1) + Double.valueOf(s2); break;
case MINUS : result = Double.valueOf(s1) - Double.valueOf(s2); break;
case TIMES : result = Double.valueOf(s1) * Double.valueOf(s2); break;
case DIVISION : result = Double.valueOf(s1) / Double.valueOf(s2); break;
default : result = null;
}
return result;
}
public static void main(String[] args) {
//String math = "9+(3-1)*3+10/2";
String math = "12.8 + (2 - 3.55)*4+10/5.0";
try {
doCalc(doMatch(math));
} catch (Exception e) {
e.printStackTrace();
}
}
}