JAVA实现计算机功能逆波兰

package Test;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

public class tomcat{

	public static void main(String[] args) {
		//1, 2, 3, +, 4, *, +, 5, -
	String exclp="1+((2+3)*4)-5";
	List<String> list=getcode(exclp);//第一步处理
System.out.println(list);
System.out.println(calc(getlastcode(list)));
}
	/**
	 * 
	 * 
	 * @param data 传需要处理的字符串 多位数
	 * @return  处理的中缀表达式子
	 */
	public static List<String> getcode(String data){
		List<String> list=new ArrayList();
		String yuan="",ok="";
		for (int i = 0; i < data.length(); i++) {
			yuan=data.substring(i,i+1);
			switch (yuan) {
			case "+":
			case "-":
			case "*":
			case "/":
			case "(":
			case ")":
				if(!ok.equals(""))
				list.add(ok);
				list.add(yuan);
				ok="";
				break;
			default:
				ok+=yuan;
				break;
			}
		}
		list.add(ok);
		
		return list;
	}
	
	/**
	 * 
	 * @param 传中缀表达
	 * @return 后缀表达
	 */
	public static List<String>  getlastcode(List<String> list) {
		Stack<String> stack=new Stack();
		List<String> listtwo=new ArrayList(list.size()); 
		for (String string : list) {//遍历我的值
			
			if(string.matches("\\d+")) {// 数字入栈
			listtwo.add(string);	
			}else if(string.equals("(")) {
				stack.push(string);
			}else if(string.equals(")")) {
				while(!stack.peek().equals("("))
					listtwo.add(stack.pop());
				stack.pop();
			}else {
				while(stack.size()!=0&&queue(stack.peek())>=queue(string)) {
					listtwo.add(stack.pop());
				}
				stack.push(string);
			}

		}
		while(!stack.isEmpty()) {
			listtwo.add(stack.pop());
		}
		return listtwo;
	}
	public static int queue(String code) {//优先级
		return    code.matches("[+-/*/]")? code.matches("[+-]")? 1:2: 0;
	}
	//传后缀计算值
	public static int calc(List<String> list) {
		Stack<String> stack=new Stack();
		for (String string : list) {
			if(string.matches("\\d+")) {//数字直接压
				stack.push(string);
			}else {//计算
				stack.push(calc(Integer.parseInt(stack.pop()),Integer.parseInt(stack.pop()),string)+"");
			}
		}
		return Integer.parseInt(stack.pop());
	}
	public static int calc(int a,int b,String code) {
			return    code.equals("+")||code.equals("-")? code.equals("+") ? a+b: b-a : code.equals("*") ? a*b:b/a;
	}
}

尚硅谷讲的非常好 我是第一次见讲数据结构那么好的

传送地址

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值