java数据结构-Stack应用:算式计算

public class StackTest {
	public static void main(String[] args) throws Exception
	{
//		MyLinStack ms=new MyLinStack();
//		ms.push(1);
//		ms.push(9);
//		ms.push(12);
//		ms.push("hah");
//		System.out.println(ms.pop());
//		System.out.println(ms.pop());
		
		String str="3+(6-4/2)*5";
		StackTest.calculateExpression(StackTest.convertExpression(str));
	}
	
	/**
	 * 计算后缀表达式
	 * @throws Exception 
	 */
	
	public static int calculateExpression(String str) throws Exception
	{
		int i1 = 0,i2=0,ii=0;
		MySeqStack mss=new MySeqStack(20);
		for(int i=0;i<str.length();i++)
		{
			char c=str.charAt(i);
			if(Character.isDigit(c))
			{
				mss.push(c);
			}
			else {
				i2=Integer.parseInt(mss.pop().toString());
				i1=Integer.parseInt(mss.pop().toString());
				ii=0;
				switch(c)
				{
				case '+':
					ii=i1+i2;
					break;
				case '-':
					ii=i1-i2;
					break;
				case '*':
					ii=i1*i2;
					break;
				case '/':
					if(i2==0)
					{
						throw new Exception("除数不能为0");
					}
					else
					{
						ii=i1/i2;
						break;
					}
					
				}
				mss.push(ii);
			}
		}
		System.out.println(mss.getTop().toString());
		return (Integer)mss.pop();
	}
	
	/**
	 * 中缀表达式转后缀表达式
	 * @throws Exception 
	 */
	
	public static String convertExpression(String str) throws Exception{
		
		StringBuffer sb=new StringBuffer();
		MySeqStack mss=new MySeqStack(20);
		for(int i=0;i<str.length();i++)//length是数组里用到的,length()是字符串里用到的
		{
			char c=str.charAt(i);
			if(Character.isDigit(c))
			{
				sb.append(c);
			}
			else{
				if(!mss.notEmpty())
				{
					mss.push(c);
				}
				else
				{
					if(c=='(')
					{
						mss.push(c);
					}
					else if(c==')')
					{
						while(!mss.getTop().equals('('))
						{
							sb.append((Character) mss.pop());
						}
						mss.pop();
					}
					
					else if(c=='+'||c=='-')
					{
						if(mss.getTop().equals('+')||mss.getTop().equals('-')||mss.getTop().equals('*')||mss.getTop().equals('/')||mss.getTop().equals(')'))
						{
							sb.append((Character) mss.pop());
							i--;
						}
						else
						{
							mss.push(c);
						}
					}
					else if(c=='*'||c=='/')
					{
						if(mss.getTop().equals('*')||mss.getTop().equals('/')||mss.getTop().equals(')'))
						{
							sb.append((Character) mss.pop());
							i--;
						}
						else
						{
							mss.push(c);
						}
					}
				}
			}
		}
		while(mss.notEmpty())
		{
			sb.append((Character)mss.pop());
		}
		System.out.println(sb.toString());
		return sb.toString();
	}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值