栈实现综合计算器(中缀表达式)
思路分析:
- 需要两个栈:数栈和符号栈 定义一个index索引来遍历表达式
- 遍历到一个数字,则入数栈
- 遍历到一个符号,若符号栈为空则入符号栈;
若符号栈不为空:如果当前遍历到的符号优先级小于或等于符号栈中符号的优先级,则从数栈中pop出两个数,从符号栈中pop出一个符号,进行运算,然后将运算结果入数栈,将当前遍历到的符号入符号栈;如果当前遍历到的符号优先级大于符号栈中符号优先级,则将该符号直接入符号栈。 - 表达式遍历完毕后,则按顺序从数栈和符号栈中pop出值进行运算
- 最后数栈中只会有一个数字 即运算结果。
代码实现:
package com.datastructures.stack;
public class Calculator {
public static void main(String[] args) {
String expression = "70+2*6-2";
//创建两个栈
ArrayStack2 numStack = new ArrayStack2(10);
ArrayStack2 operStack = new ArrayStack2(10);
int index = 0;//用于扫描表达式
int num1 = 0;
int num2 = 0;
int oper = 0;
int res = 0;
char ch = ' ';
String keepNum = "";//用于拼接多位数
while (true) {
ch = expression.substring(index, index + 1).charAt(0);
if (operStack.isOper(ch)) {//扫描到是符号
if (!operStack.isEmpty()) {
//如果当前遍历到的符号优先级小于或等于符号栈中符号的优先级,
//则从数栈中pop出两个数,从符号栈中pop出一个符号,进行运算,
// 然后将运算结果入数栈,将当前遍历到的符号入符号栈;
if (operStack.priority(ch) <= operStack.priority(operStack.peek())) {
num1 = numStack.pop();
num2 = numStack.pop();
oper = operStack.pop();
res = numStack.cal(num1, num2, oper);
numStack.push(res);
operStack.push(ch);
} else {
//如果**当前遍历到的符号优先级大于符号栈中符号优先级**,则将该符号直接入符号栈
operStack.push(ch);
}
} else {
//若符号栈为空则入符号栈;
operStack.push(ch);
}
} else {//扫描到是数字
//numStack.push(ch-48);
//处理多位数:
// 当index扫描到数字后 再往后扫描一位 若后一位是符号则将该数字入数栈 否则继续扫描
// 需要定义一个变量字符串用于拼接数字
//如果ch已经是expression的最后一位则直接入栈
keepNum += ch;
if (index == expression.length() - 1) {
numStack.push(Integer.parseInt(keepNum));
} else {
if (operStack.isOper(expression.substring(index + 1, index + 2).charAt(0))) {
numStack.push(Integer.parseInt(keepNum));
//注意要将keepNum清空
keepNum = "";
}
}
}
index++;
if (index >= expression.length()) {
break;
}
}
//表达式遍历完毕后,则按顺序从数栈和符号栈中pop出值进行运算
while (true) {
if (operStack.isEmpty()) {
break;
}
num1 = numStack.pop();
num2 = numStack.pop();
oper = operStack.pop();
res = numStack.cal(num1, num2, oper);
numStack.push(res);
}
System.out.printf("表达式%s的结果为:%d", expression, numStack.pop());
}
}
class ArrayStack2 {
private int maxSize;//栈的最大容量
private int[] stack;//定义一个数组 栈的数据存在数组中
private int top = -1;//指向栈顶
public ArrayStack2(int maxSize) {
this.maxSize = maxSize;
stack = new int[maxSize];
}
//栈满
public boolean isFull() {
return top == maxSize - 1;
}
//栈空
public boolean isEmpty() {
return top == -1;
}
//显示当前栈顶元素
public int peek() {
return stack[top];
}
//入栈
public void push(int data) {
if (isFull()) {
System.out.printf("栈满,无法入栈");
return;
} else {
top++;
stack[top] = data;
}
}
//出栈
public int pop() {
if (isEmpty()) {
throw new RuntimeException("栈空");
} else {
int value = stack[top];
top--;
return value;
}
}
//显示栈
public void show() {
if (isEmpty()) {
throw new RuntimeException("栈空");
} else {
for (int i = top; i >= 0; i--) {
System.out.printf("stack[%d]=%d\n", i, stack[i]);
}
}
}
//返回运算符的优先级 规定数字越大优先级越高
public int priority(int oper) {
if (oper == '*' || oper == '/') return 1;
else if (oper == '+' || oper == '-') return 0;
else return -1;//假设当前只有+ - * /四种符号
}
//判断是否是符号
public boolean isOper(int oper) {
return oper == '+' || oper == '-' || oper == '*' || oper == '/';
}
//定义运算规则
public int cal(int num1, int num2, int oper) {
int res = 0;
switch (oper) {
case '+':
res = num1 + num2;
break;
case '-':
res = num2 - num1;
break;
case '*':
res = num1 * num2;
break;
case '/':
res = num2 / num1;
break;
default:
break;
}
return res;
}
}
逆波兰计算器的代码实现:(只支持对整数)
前缀:从右到左计算
后缀:从左到右计算
package com.datastructures.stack;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
public class PolandNotation {
public static void main(String[] args) {
//定义一个逆波兰表达式 (3+4)*5-6=> 3 4 + 5 * 6 -
String suffixExpression = "3 4 + 5 * 6 -";
List<String> rpnList = getListString(suffixExpression);
System.out.println("rpnList=" + rpnList);
int res=cal(rpnList);
System.out.println("计算结果是:"+res);
}
public static List<String> getListString(String suffixExpression) {
//将表达式中数字和符号放入到ArrayList中
String[] split = suffixExpression.split(" ");
List<String> list = new ArrayList<String>();
for (String ele : split) {
list.add(ele);
}
return list;
}
/*
计算步骤:
1)从左至右扫描,将3和4压入堆栈
2)遇到+运算符,弹出栈顶元素4和次顶元素3 计算3+4的值 将其入栈
3)5入栈
4)遇到* 弹出5,7 计算结果入栈
5)6入栈
6)遇到- 弹出35,6 计算结果
*/
public static int cal(List<String> ls) {
Stack<String> stack = new Stack<>();
//遍历list集合
for (String i : ls) {
if (i.matches("\\d+")) {
stack.push(i);
} else {
int num2 = Integer.parseInt(stack.pop());
int num1 = Integer.parseInt(stack.pop());
int res = 0;
if (i.equals("+")) {
res = num1 + num2;
} else if (i.equals("-")) {
res = num1 - num2;
} else if (i.equals("*")) {
res = num1 * num2;
} else if (i.equals("/")) {
res = num1 / num2;
}else{
throw new RuntimeException("运算符有误!");
}
stack.push("" + res);
}
}
return Integer.parseInt(stack.pop());
}
}
中缀表达式转后缀表达式:
中缀表达式 1 + ( ( 2 + 3 )× 4) - 5 =》 后缀表达式
将 s2 出栈 - 5 + * 4 + 3 2 1 => 1 2 3 + 4 * + 5 -
步骤:
-
初始化两个栈:运算符栈s1和储存中间结果的栈s2;
-
从左至右扫描中缀表达式;
-
遇到操作数时,将其压s2;
-
遇到运算符时,比较其与s1栈顶运算符的优先级:
- 如果s1为空,或栈顶运算符为左括号“(”,则直接将此运算符入栈;
- 否则,若优先级比栈顶运算符的高,也将运算符压入s1;
- 否则,将s1栈顶的运算符弹出并压入到s2中,再次转到4.1与s1中新的栈顶运算符相比较;
-
遇到括号时:
如果是左括号“(”,则直接压入s1
如果是右括号“)”,则依次弹出s1栈顶的运算符,并压入s2,直到遇到左括号为止,此时将这一对括号丢弃 -
重复步骤2至5,直到表达式的最右边
-
将s1中剩余的运算符依次弹出并压入s2
-
依次弹出s2中的元素并输出,结果的逆序即为中缀表达式对应的后缀表达式
代码实现:
package com.datastructures.stack;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
public class PolandNotation {
public static void main(String[] args) {
//1、完成将中缀表达式转成后缀表达式的功能1+((2+3)*4)-5 => 1 2 3 + 4 * + 5 -
//因为直接对表达式进行操作不方便 因此先将“1+((2+3)*4)-5”=>中缀表达式对应的List
//即 “1+((2+3)*4)-5”=>ArrayList[1,+,(,(,2,+,3,),*,4,),-,5]
String expression = "1+((2+3)*4)-5";
List<String> infixExpressionList = toInfixExpressionList(expression);
System.out.println("中缀表达式对应的List:"+infixExpressionList);
List<String> suffixExpressionList = parseSuffixExpressionList(infixExpressionList);
System.out.println("后缀表达式对应的List:"+suffixExpressionList);
int res = cal(suffixExpressionList);
System.out.println("计算结果是:"+res);
/* //定义一个逆波兰表达式 (3+4)*5-6=> 3 4 + 5 * 6 -
String suffixExpression = "3 4 + 5 * 6 -";
List<String> rpnList = getListString(suffixExpression);
System.out.println("rpnList=" + rpnList);
int res=cal(rpnList);
System.out.println("计算结果是:"+res);*/
}
//2、将中缀表达式转成对应的List s="1+((2+3)*4)-5" => ArrayList[1,+,(,(,2,+,3,),*,4,),-,5]
public static List<String> toInfixExpressionList(String s) {
//定义一个List存放中缀表达式对应的内容
List<String> ls = new ArrayList<String>();
int i = 0;// 指针,用于遍历
String str;//用于多位数的拼接
char c;//每遍历到一个字符就放入c
do {
//如果c是非数字则直接加入ls
if ((c = s.charAt(i)) < 48 || (c = s.charAt(i)) > 57) {
ls.add("" + c);
i++;
} else {//如果c是数字 则需要考虑多位数
str = "";//将str清空
while (i < s.length() && (c = s.charAt(i)) >= 48 && (c = s.charAt(i)) <= 57) {
str += c;//拼接
i++;
}
ls.add(str);
}
} while (i < s.length());
return ls;
}
//3、将得到的中缀表达式List转成后缀表达式对应的List
// 即ArrayList[1,+,(,(,2,+,3,),*,4,),-,5]=>ArrayList[1,2,3,+,4,*,+,5,-]
public static List<String> parseSuffixExpressionList(List<String> ls) {
//1) 初始化两个栈:**运算符栈s1和储存中间结果的栈s2**;
Stack<String> s1 = new Stack<String>();//运算符栈s1
//因为在整个转换过程中s2并没有进行pop操作 且最后需要逆序输出s2内容
//因此为了方便 可以使用List<String>集合来代替Stack<String>
List<String> s2 = new ArrayList<String>();//储存中间结果的List<String> s2;
int index = 0;//用于扫描表达式
//2)遍历ls
for (String item : ls) {
//如果是一个数,则加入s2
if (item.matches("\\d+")) {
s2.add(item);
} else if (item.equals("(")) {
s1.push(item);
} else if (item.equals(")")) {
// 如果是**右括号“)”**,则依次弹出s1栈顶的运算符,并压入s2,直到遇到左括号为止,此时将这一对括号丢弃
while (!s1.peek().equals("(")) {
s2.add(s1.pop());
}
s1.pop();//将“(”弹出s1消除小括号
}else{
//将s1栈顶的运算符弹出并压入到s2中,再次转到4.1与s1中新的栈顶运算符相比较
while(s1.size()!=0&&Operation.getValue(s1.peek())>=Operation.getValue(item)){
s2.add(s1.pop());
}
s1.push(item);
}
}
//将s1中剩余的运算符依次弹出并加入s2中
while (s1.size()!=0){
s2.add(s1.pop());
}
return s2;//因为s2是List集合 所以它的顺序输出就是后缀表达式
}
public static List<String> getListString(String suffixExpression) {
//将表达式中数字和符号放入到ArrayList中
String[] split = suffixExpression.split(" ");
List<String> list = new ArrayList<String>();
for (String ele : split) {
list.add(ele);
}
return list;
}
/* 计算步骤:
1)从左至右扫描,将3和4压入堆栈
2)遇到+运算符,弹出栈顶元素4和次顶元素3 计算3+4的值 将其入栈
3)5入栈
4)遇到* 弹出5,7 计算结果入栈
5)6入栈
6)遇到- 弹出35,6 计算结果*/
public static int cal(List<String> ls) {
Stack<String> stack = new Stack<>();
//遍历list集合
for (String i : ls) {
if (i.matches("\\d+")) {
stack.push(i);
} else {
int num2 = Integer.parseInt(stack.pop());
int num1 = Integer.parseInt(stack.pop());
int res = 0;
if (i.equals("+")) {
res = num1 + num2;
} else if (i.equals("-")) {
res = num1 - num2;
} else if (i.equals("*")) {
res = num1 * num2;
} else if (i.equals("/")) {
res = num1 / num2;
} else {
throw new RuntimeException("运算符有误!");
}
stack.push("" + res);
}
}
return Integer.parseInt(stack.pop());
}
}
//编写Operation类可以返回运算符对应的优先级
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 res=0;
switch(operation){
case "+":
res=ADD;
break;
case "-":
res=SUB;
break;
case "*":
res=MUL;
break;
case "/":
res=DIV;
break;
default:
System.out.println("不存在运算符!");
break;
}
return res;
}
}