java中栈的应用

一、使用栈实现中缀表达式的计算

思路

  1. 建立两个栈,一个用于存放数值number,一个用于存放运算符chs
  2. 遇到数值,则直接将数值压入number中
  3. 遇到运算符,这里不包括括号,如果chs中栈顶的运算符优先级大于等于当前运算符,则在number中栈顶弹出两个数值,chs栈顶弹出一个运算符进行计算,并将计算结果压入栈中,重复该操作知道chs栈顶运算符优先级小于当前运算符优先级
  4. 运算符优先级小于栈顶优先级,直接压入chs
  5. 遇到(,直接压入chs
  6. 遇到),在number中栈顶弹出两个数值,chs栈顶弹出一个运算符进行计算,重复该操作知道chs栈顶为(,并将 ( 弹出栈
  7. 最终number和chs全部数据出栈,计算得到最终结果,number剩下的最后一个值就是为最终结果

代码

public class StackDemo {
	
	//创建数值栈
	static Stack<Integer> number = new Stack<>();
	//创建符号栈
	static Stack<Character> chs = new Stack<>();
	
	//判断操作符的优先级
	public static int priotity(char ch) {
		if (ch=='+' || ch=='-') {
			return 1;
		} else if (ch=='*' || ch=='/') {
			return 2;
		} else if (ch=='(' || ch==')') {
			return -1;
		}
		return 0;
	}
	
	//计算结果
	public static int cal(int a, int b, char ch) {
		if (ch=='+') {
			return a+b;
		} else if (ch=='-') {
			return a-b;
		} else if (ch=='*') {
			return a*b;
		} else if (ch=='/') {
			return a/b;
		}
		return 0;
	}
	
	//计算结果并将结果压入栈中
	public static void getAns() {
		int t1 = number.pop();
		int t2 = number.pop();
		int ans = cal(t2, t1, chs.pop());
		number.push(ans);//将计算结果压入栈中
		//System.out.println("ans = " + ans);
	}
	
	//计算中缀表达式的结果
	public static void calRes(String str) {
		char a[] = str.toCharArray();
		for(int i=0; i<a.length; i++) { //遍历整个算术
			int temp = priotity(a[i]); //判断是否是运算符
			if (temp==0) {
				int num = a[i] - 48;
				int j = i+1;
				for(j=i+1; j<a.length; j++) { //将整个数值叠加,防止数位丢失
					if (priotity(a[j])==0) {
						num = num*10 + (a[j] - 48);
					} else {
						break;
					}
				}
				i = j-1;
				number.push(num); //将数值存放到栈之中
			} else {
				if (chs.isEmpty()) {
					chs.push(a[i]);
				} else if(a[i]==')') { //扫描到")",先将括号中的值计算得出
					while(chs.peek()!='(') {
						getAns();
						System.out.println(number.peek());
					}
					chs.pop();
				} else if (a[i]=='(') {
					chs.push(a[i]); //如果是'(',则直接压入栈
				} else {
					int perOper = priotity(chs.peek());
					if (perOper >= temp) { //如果栈顶的运算符优先级比当前运算符的优先级高,并且栈顶的运算符不是括号,则计算栈顶两个数值的值
						getAns();
						i--;  //继续判断该符号是否大于等于栈顶符号
					} else {
						chs.push(a[i]); //将当前符号压入符号栈中
					}
				}
			}
		}
		//遍历符号栈,计算最终的结果
		while(!chs.isEmpty()) {
			getAns();
		}
		System.out.println(str + " = " + number.pop());
	}
	
	public static void main(String[] args) {
		String str = "1+2*4+(10-3*11+11)+60-9+8*6";
		calRes(str);
	}
}

二、中缀表达式转化为后缀表达式

思路

  1. 初始化两个栈:运算符栈 s1 和储存中间结果的栈 s2
  2. 从左至右扫描中缀表达式
  3. 遇到操作数时,将其压 s2
  4. 遇到运算符时,比较其与 s1 栈顶运算符的优先级:1).如果 s1 为空,或栈顶运算符为左括号“(”,则直接将此运算符入栈;2).否则,若优先级比栈顶运算符的高,也将运算符压入 s1;3).否则,将 s1 栈顶的运算符弹出并压入到 s2 中,再次转到(4.1)与 s1 中新的栈顶运算符相比较
  5. 遇到括号时:1) 如果是左括号“(”,则直接压入 s12) 如果是右括号“)”,则依次弹出 s1 栈顶的运算符,并压入 s2,直到遇到左括号为止,此时将这一对括号丢弃
  6. 重复步骤 2 至 5,直到表达式的最右边
  7. 将 s1 中剩余的运算符依次弹出并压入 s2
  8. 依次弹出 s2 中的元素并输出,结果的逆序即为中缀表达式对应的后缀表达式

代码

//中缀表达式转换成后缀
public class InfixToPostfix {
	
	//初始化一个符号栈,相当于S1
	static Stack<String> chs = new Stack<>();
	//初始化列表用于存储最终的结果,相当于S2,由于对S2的处理只需要入栈,没有其他相关操作,因此使用list即可
	static List<String> postfix = new ArrayList<String>();
	
	//判断操作符的优先级
	public static int priotity(String ch) {
		if (ch.equals("+") || ch.equals("-")) {
			return 1;
		} else if (ch.equals("*") || ch.equals("/")) {
			return 2;
		} else if (ch.equals("(") || ch.equals(")")) {
			return -1;
		}
		return 0;
	}
	
	//将中缀表达式转化为后缀
	public static void solve(String str) {
		//将字符串进行分割
		String res[] = str.split("");
		for(int i=0; i<res.length; i++) {
			System.out.println(res[i]);
			int temp = priotity(res[i]);
			if (temp==0) {
				String num = res[i];
				int j = i+1;
				for(j=i+1; j<res.length; j++) { //将整个数值叠加,防止数位丢失
					if (priotity(res[j])==0) {
						num += res[j]; 
					} else {
						break;
					}
				}
				i = j-1;
				//将数值压入栈之中
				postfix.add(num);
			} else {
				if (res[i].equals("(")) { //如果遇到左括号,则直接压入栈
					chs.push(res[i]);
				} else if (res[i].equals(")")) { //如果遇到右括号,依次将运算符压入栈,直到遇到左括号
					while(!chs.peek().equals("(")) {
						postfix.add(chs.pop());
					}
					chs.pop();
				} else if (chs.isEmpty()) { //栈为空,直接压入栈
					chs.push(res[i]);
				} else { //如果是运算符,将栈中比当前运算符的优先级低的加入到列表中,并将该运算符压入栈中
					while(!chs.isEmpty() && priotity(chs.peek())>=temp) {
						postfix.add(chs.pop());
					}
					chs.push(res[i]);
				}
			}
		}
		
		//将栈中的符号都记录到数组中
		while(!chs.isEmpty()) {
			postfix.add(chs.pop());
		}
		
		System.out.println("中缀表达式:" + str);
		System.out.println("后缀表达式:" + postfix);
 	}
	
	public static void main(String[] args) {
		String str = "781+((2+303)*44)-512";
		solve(str);
	}
}

三、计算后缀表达式的值

思路

  1. 遍历中缀转化为后缀表达式的列表postfix
  2. 如果是数值,则加入数值栈中number
  3. 如果是运算符,则从number中栈顶弹出两个数值,并将计算结果压入栈中
  4. number剩下的最后一个值即为最终答案

代码

//计算结果
public static int cal(int a, int b, String ch) {
	if (ch.equals("+")) {
		return a+b;
	} else if (ch.equals("-")) {
		return a-b;
	} else if (ch.equals("*")) {
		return a*b;
	} else if (ch.equals("/")) {
		return a/b;
	}
	return 0;
}
//计算结果并将结果压入栈中
public static void getAns(String oper) {
	int t1 = number.pop();
	int t2 = number.pop();
	int ans = cal(t2, t1, oper);
	number.push(ans);//将计算结果压入栈中
}
		
//使用后缀表达式进行计算
public static void calPostfix() {
	//遍历列表
	for(String str : postfix) {
		if(str.matches("\\d+")) { //如果是数值,直接压入栈
			number.push(Integer.parseInt(str));
		} else {
			getAns(str);
		}
	}
	System.out.println(number.pop());
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值