栈与逆波兰表达式计算(java)
栈的应用场景:
1.使用数组模拟栈
使用数组模拟栈的push、pop、遍历等操作
实现代码:
import java.util.Scanner;
/**
* @author HP
* @since 2021/3/8
*/
public class ArrayStackDemo {
public static void main(String[] args) {
ArrayStack stack = new ArrayStack(5);
String key = "";
boolean loop = true;//控制是否退出程序
Scanner scanner = new Scanner(System.in);
while (loop) {
System.out.println("show:显示栈");
System.out.println("exit:退出程序");
System.out.println("push:入栈");
System.out.println("pop:出栈");
System.out.println("请输入操作:");
key = scanner.next();
switch (key) {
case "show":
stack.list();
break;
case "exit":
loop = false;
scanner.close();
break;
case "push":
int value = scanner.nextInt();
stack.push(value);
break;
case "pop":
try {
int top = stack.pop();
System.out.println("出栈:" + top);
} catch (Exception e) {
System.out.println(e.getMessage());
}
break;
default:
break;
}
}
System.out.println("程序执行完毕");
}
}
//定义一个ArrayStack模拟栈
class ArrayStack {
private int maxSize;//栈的大小
private int[] stack;//数组模拟栈
private int top = -1;//指向栈顶,初始值为-1
//构造器,初始化栈
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 value) {
//判断栈是否满
if (isFull()) {
System.out.println("栈满");
return;
}
top++;
stack[top] = value;
}
//出栈
public int pop() {
//判断栈是否空
if (isEmpty()) {
throw new RuntimeException("栈空,没有数据");
}
int value = stack[top];
top--;
return value;
}
//遍历栈
public void list() {
if (isEmpty()) {
System.out.println("栈空,没有数据");
return;
}
//从栈顶开始遍历
for (int i = top; i >= 0; i--) {
System.out.printf("stack[%d]=%d\n", i, stack[i]);
}
}
}
2.使用栈计算数学表达式(中缀表达式)
实现代码:
/**
* @author HP
* @since 2021/3/8
*/
public class Calculator {
public static void main(String[] args) {
String expression = "200*3+3-20";
//创建两个栈,一个数字栈,一个符号栈
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 = ' ';//将每次扫描得到的char保存在ch
String keepNum = "";//用于拼接多位数
//开始循环扫描expression
while (true) {
//依次得到expression的每个字符
ch = expression.charAt(index);
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 {
//扫描到数字
keepNum += ch;
//如果ch已经是表达式最后一位,就直接入栈
if (index == expression.length() - 1) {
numStack.push(Integer.parseInt(keepNum));
} else {
if (operStack.isOper(expression.charAt(index + 1))) {
numStack.push(Integer.parseInt(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);
}
//数栈的最后一个数就是结果
res = numStack.pop();
System.out.printf("表达式%s=%d\n", expression, res);
}
}
//定义一个ArrayStack模拟栈
class ArrayStack2 {
private int maxSize;//栈的大小
private int[] stack;//数组模拟栈
private int top = -1;//指向栈顶,初始值为-1
//构造器,初始化栈
public ArrayStack2(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 value) {
//判断栈是否满
if (isFull()) {
System.out.println("栈满");
return;
}
top++;
stack[top] = value;
}
//出栈
public int pop() {
//判断栈是否空
if (isEmpty()) {
throw new RuntimeException("栈空,没有数据");
}
int value = stack[top];
top--;
return value;
}
//遍历栈
public void list() {
if (isEmpty()) {
System.out.println("栈空,没有数据");
return;
}
//从栈顶开始遍历
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(char val) {
return val == '+' || val == '-' || val == '*' || val == '/';
}
//查看栈顶元素
public int peek() {
return stack[top];
}
//计算方法
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;
default:
break;
}
return result;
}
}
3.前缀表达式(波兰表达式)
完整代码:
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
/**
* 计算后缀表达式(逆波兰表达式)
*
* @author HP
* @since 2021/3/8
*/
public class PolandNotation {
public static void main(String[] args) {
//(3+4)*5-6 -->"3 4 + 5 * 6 -"
//为了方便,逆波兰表达式的数字和符号使用空格隔开
String suffixExpression = "3 4 + 5 * 6 -";
//思路:
//1.先将"3 4 + * 6 -"放到ArrayList中
//2.将ArrayList传递给一个方法,遍历ArrayList配合完成计算
List<String> rpnList = getListString(suffixExpression);
int result = calculate(rpnList);
System.out.println(result);
}
//将一个逆波兰表达式依次将数据和运算符放入到ArrayList中
public static List<String> getListString(String suffixExpression) {
//将suffixExpression分割
String[] split = suffixExpression.split(" ");
List<String> list = new ArrayList<>();
for (String ele : split) {
list.add(ele);
}
return list;
}
//计算逆波兰表达式
public static int calculate(List<String> ls) {
//创建栈,只需要一个栈即可
Stack<String> stack = new Stack<>();
//遍历ls
for (String item : ls) {
//使用正则表达式匹配出数字
if (item.matches("\\d+")) {
//入栈
stack.push(item);
} else {
//扫描到操作符
//pop出两个数,运算,然后把结果入栈
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());
}
}
4.中缀表达式转后缀表达式
完整代码实现:
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
/**
* 计算后缀表达式(逆波兰表达式)
*
* @author HP
* @since 2021/3/8
*/
public class PolandNotation {
public static void main(String[] args) {
// //(3+4)*5-6 -->"3 4 + 5 * 6 -"
// //为了方便,逆波兰表达式的数字和符号使用空格隔开
// String suffixExpression = "3 4 + 5 * 6 -";
// //思路:
// //1.先将"3 4 + * 6 -"放到ArrayList中
// //2.将ArrayList传递给一个方法,遍历ArrayList配合完成计算
// List<String> rpnList = getListString(suffixExpression);
//
// int result = calculate(rpnList);
//
// System.out.println(result);
String expression = "1+(20+4)/4-5";
//将中缀表达式转换成list
List<String> infixExpressionList = toInfixExpressionList(expression);
System.out.println(infixExpressionList);
//将中缀表达式对应的list转为后缀表达式的list
List<String> parseSuffixExpressionList = parseSuffixExpressionList(infixExpressionList);
System.out.println(parseSuffixExpressionList);
//根据后缀表达式的list,计算出结果
int result = calculate(parseSuffixExpressionList);
System.out.println(result);
}
//将一个逆波兰表达式依次将数据和运算符放入到ArrayList中
public static List<String> getListString(String suffixExpression) {
//将suffixExpression分割
String[] split = suffixExpression.split(" ");
List<String> list = new ArrayList<>();
for (String ele : split) {
list.add(ele);
}
return list;
}
//计算逆波兰表达式
public static int calculate(List<String> ls) {
//创建栈,只需要一个栈即可
Stack<String> stack = new Stack<>();
//遍历ls
for (String item : ls) {
//使用正则表达式匹配出数字
if (item.matches("\\d+")) {
//入栈
stack.push(item);
} else {
//扫描到操作符
//pop出两个数,运算,然后把结果入栈
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());
}
//将中缀表达式转成对应的list
public static List<String> toInfixExpressionList(String s) {
//定义一个List,春风中缀表达式对应的内容
List<String> ls = new ArrayList<>();
int i = 0;//用于遍历表达式
String str;//用于多位数的拼接
char c;//每遍历到一个字符就放入c中
do {
//如果是一个非数字就加入到ls中
if ((c = s.charAt(i)) < 48 || (c = s.charAt(i)) > 57) {
ls.add("" + c);
i++;
} else {
//如果是一个数,需要考虑这个数是多位数
str = "";
while (i < s.length() && (c = s.charAt(i)) >= 48 && (c = s.charAt(i)) <= 57) {
str += c;//拼接多位数
i++;
}
//将拼接到的多位数添加到ls中
ls.add(str);
}
} while (i < s.length());
return ls;
}
//将得到的中缀表达式对应的List => 后缀表达式的List
public static List<String> parseSuffixExpressionList(List<String> ls) {
//定义两个栈
Stack<String> s1 = new Stack<>();//符号栈
//说明:因为s2这个栈在整个转换过程中没有pop操作,而且最后的结果还要逆序输出,所以这里时s2这个栈直接使用List代替即可
// Stack<String> s2 =
List<String> s2 = new ArrayList<>();//存储中间结果的列表s2
//遍历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();
} else {
//当item的优先级小于等于s1栈顶的运算符,将s1栈顶运算符加入到s2中
while (s1.size() != 0 && Operation.getValue(s1.peek()) >= Operation.getValue(item)) {
s2.add(s1.pop());
}
//还需要将item压入栈
s1.push(item);
}
}
//将s1中剩余的运算符依次弹出并加入s2
while (s1.size() != 0) {
s2.add(s1.pop());
}
return s2;
}
}
//编写一个类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 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;
}
}