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();
}
java数据结构-Stack应用:算式计算
于 2018-08-22 20:15:04 首次发布