堆栈应用:表达式计算

package new03;


import java.util.Stack;


public class Dmeo2 {



/*
* 表达式计算(堆栈实现)
* */

public static String result="";
public static Stack s = new Stack();

public static void main(String[] args){
// String str = "a+b*c+(d*e+f)*g";
String str = "6*(5+(2+3)*8+3)";
char[] ch = str.toCharArray();

for(int i=0;i char temp = ch[i];
switch(temp){
case '(':
s.push(temp);
break;

case ')':
fun();
break;

case '+':
case '-':
fun1();
s.push(temp);
break;

case '*':
case '/':
fun2();
s.push(temp);
break;


default:
result = result + temp;
}
}

while(s.size()!=0){
result = result+s.pop();
}

System.out.println(result);

System.out.println(calculate(result));

}


private static void fun() {
while(true){
if(s.size()==0)
break;
Character c = (Character) s.pop();
if(c!='('){
result = result+c;
}
else
break;
}
}


private static void fun2() {
while(true){
if(s.size()==0)
break;
Character c = (Character) s.pop();
if(c=='*' || c=='/' )
result = result +c;
else
{
s.push(c);
break;
}
}
}


private static void fun1() {
while(true){
if(s.size()==0)
break;
Character c = (Character) s.pop();
if(c=='+' || c=='-' || c=='*' || c=='/' )
result = result +c;
else
{
s.push(c);
break;
}
}
}

//后缀表达式的计算
public static int calculate(String result){
Stack stack = new Stack();
char[] chs = result.toCharArray();
for(int i=0;i char t = chs[i];
switch(t){
case '+':
int num2 = stack.pop();
int num1 = stack.pop();
int num = num1+num2;
stack.push(num);
break;
case '-':
num2 = stack.pop();
num1 = stack.pop();
num = num1-num2;
stack.push(num);
break;
case '*':
num2 = stack.pop();
num1 = stack.pop();
num = num1*num2;
stack.push(num);
break;
case '/':
num2 = stack.pop();
num1 = stack.pop();
num = num1/num2;
stack.push(num);
break;
default:
int x = Integer.parseInt(t+"");
stack.push(x);
break;
}
}


return stack.pop();

}

}

你可能感兴趣的:(程序员面试经典100题)