栈实现表达式计算

计算器实现与表达式求值

在这里插入图片描述

package com.pro.stack;

public class CalculatorTest {

	public static void main(String[] args) {
		String expression = "7*2*2-5+1-5+3-4";
		// 创建两个栈,数栈,一个符号栈
		CalculatorStack numStack = new CalculatorStack(10);
		CalculatorStack operStack = new CalculatorStack(10);
		// 定义相关变量
		int index = 0;// 用于扫描
		int num1 = 0;
		int num2 = 0;
		int oper = 0;
		int res = 0;
		int ch = ' ';// 将每次扫描得到的char保存到ch
		String keepNum="";//用于拼接多位数
		while (true) {
			// 依次得到expression的每一个字符
			ch = expression.substring(index, index+1).charAt(0);
			
			// 判断ch是什么,然后做相应处理
			if (operStack.isOper((char) ch)) {// 如果是运算符
				// 判断当前符号栈是否为空,不为空就进行比较操作符的优先级
				if (!operStack.isEmpty()) {
					// 若优先级小于或等于当前栈中操作数的优先级,就需要pop出两个数,
					// 并从符号栈中pop出一个符号,进行运算,将的得到结果,入数栈,然后将当前的操作符入栈
					if (operStack.prioty(ch) <= operStack.prioty(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);// 1+3
				}
			} else {// 如果是数,直接入数栈
//				numStack.push(ch - 48);
				
				//处理多位数
				
				keepNum+=(ch-48);
				
				//如果ch已经是expression的最后一位,就直接入栈
				if (index == expression.length() - 1) {
					numStack.push(Integer.parseInt(keepNum));
				}else{
				
					//判断下一个字符是不是数字,如果是数字,就继续扫描,如果是运算符,则入栈
					//注意是看后一位,不是index++
					if (operStack.isOper(expression.substring(index+1,index+2).charAt(0))) {
						//如果后一位是运算符,则入栈 keepNum = "1" 或者 "123"
						numStack.push(Integer.parseInt(keepNum));
						//重要的!!!!!!, keepNum清空
						keepNum = "";	
					}
				}
			}
			// 让index+1,并盘算是否扫描到expression最后
			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.println("表达式" + expression + "=" + numStack.pop());

	}

}
package com.pro.stack;

public class CalculatorStack {
	private int maxSize;//栈的大小
	private int[] stack;//数组,数组模拟栈,数据就放在该数组中
	private int top=-1;//top表示栈顶,初始化为-1
	
	//构造
	public CalculatorStack(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 int peek() {
		return stack[top];
	}
	
	//遍历栈
	public void list() {
		if (isEmpty()) {
			System.out.println("栈空,没有数据~~");
			return;
		}
		for (int i = top; i >=0; i--) {
			System.out.println("stack["+i+"]="+stack[i]);
		}
	}
	
	//返回运算符的优先级,优先级有程序员确定.优先级使用数字表示,
	//数字越大,则优先级越高
	 public int prioty(int oper) {
		if(oper=='*'||oper=='/'){
			return 1;
		}else if (oper=='+'||oper=='-') {
			return 0;
		}else{
			return -1;
		}
	}
	
	//判断是不是元素符
	 public boolean isOper(char ch) {
		return ch=='+'||ch=='-'||ch=='*'||ch=='/';
	}
	
	 //计算方法
	 public int cal(int num1,int num2,int oper) {
		int res=0;//res 用于存放计算的结果
		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;
	} 
}
在 Java 中,可以使用实现表达式计算,下面是一个使用实现表达式计算的示例代码,包括中缀表达式转后缀表达式以及后缀表达式计算: ```java import java.util.*; public class ExpressionCalculator { // 中缀表达式转后缀表达式 public static List<String> infixToPostfix(String infix) { List<String> postfix = new ArrayList<>(); Stack<Character> operatorStack = new Stack<>(); int i = 0; while (i < infix.length()) { char ch = infix.charAt(i); if (Character.isDigit(ch)) { StringBuilder num = new StringBuilder(); while (i < infix.length() && (Character.isDigit(infix.charAt(i)) || infix.charAt(i) == '.')) { num.append(infix.charAt(i++)); } postfix.add(num.toString()); i--; } else if (ch == '(') { operatorStack.push(ch); } else if (ch == ')') { while (!operatorStack.isEmpty() && operatorStack.peek() != '(') { postfix.add(operatorStack.pop() + ""); } operatorStack.pop(); // 弹出 '(' } else if (isOperator(ch)) { while (!operatorStack.isEmpty() && operatorStack.peek() != '(' && precedence(operatorStack.peek()) >= precedence(ch)) { postfix.add(operatorStack.pop() + ""); } operatorStack.push(ch); } i++; } while (!operatorStack.isEmpty()) { postfix.add(operatorStack.pop() + ""); } return postfix; } // 判断是否为运算符 private static boolean isOperator(char ch) { return ch == '+' || ch == '-' || ch == '*' || ch == '/'; } // 运算符优先级 private static int precedence(char operator) { switch (operator) { case '+': case '-': return 1; case '*': case '/': return 2; default: return 0; } } // 后缀表达式计算 public static int Calculation(List<String> ls) { Stack<String> stack = new Stack<>(); for (String item : ls) { 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()); } public static void main(String[] args) { String infix = "10+((2+3)*4)-5"; List<String> postfix = infixToPostfix(infix); int result = Calculation(postfix); System.out.println("表达式 " + infix + " 的计算结果是: " + result); } } ``` 上述代码中,`infixToPostfix` 方法用于将中缀表达式转换为后缀表达式,`Calculation` 方法用于计算后缀表达式的值。`precedence` 方法用于确定运算符的优先级,`isOperator` 方法用于判断一个字符是否为运算符。 ### 代码解释 1. **中缀表达式转后缀表达式**: - 遍历中缀表达式,遇到数字直接添加到后缀表达式列表中。 - 遇到左括号 `(` 直接压入运算符。 - 遇到右括号 `)` 时,将运算符中的运算符弹出并添加到后缀表达式列表中,直到遇到左括号 `(`,然后将左括号弹出。 - 遇到运算符时,比较其与顶运算符的优先级,若顶运算符优先级高,则将顶运算符弹出并添加到后缀表达式列表中,直到顶运算符优先级低于当前运算符或为空,然后将当前运算符压入。 2. **后缀表达式计算**: - 遍历后缀表达式,遇到数字直接压入。 - 遇到运算符时,从中弹出两个数字进行运算,将结果压入。 - 最后中剩下的数字即为表达式的结果。
评论 2
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值