package org.lazyzhong.MyStack;
import java.util.Stack;
public class test1 {
static Stack stack = new Stack();
static Stack stack1 = new Stack();
static String newstr="";
public static void main(String[] args) {
String myimg="2*(1+3)-5*(1+2)";
System.out.println(toSuffixExpression(myimg));
System.out.println(doParse(toSuffixExpression(myimg)));
}
public static String toSuffixExpression(String mystr) {
for(int i=0;i<mystr.length();i++){
char ch=mystr.charAt(i);
switch(ch){
case '+':
case '-':
getOP(ch,1);
break;
case '*':
case '/':
getOP(ch,2);
break;
case '(':
stack.push(ch);
break;
case ')':
getParen(ch);
break;
default:
newstr+=ch;
break;
}
}
while(!stack.isEmpty()){
newstr+=stack.pop();
}
return newstr;
}
public static void getOP(char ch,int p){
while(!stack.isEmpty()){
char op=(char) stack.pop();
if(op=='('){
stack.push(op);
break;
}else{
int p2;
if(op=='+' || op=='-')
p2=1;
else p2=2;
if(p2<p){
stack.push(op);
break;
}
else{
newstr+=op;
}
}
}
stack.push(ch);
}
public static void getParen(char ch){
while(!stack.isEmpty()){
char chx=(char) stack.pop();
if(chx=='(')
break;
else
newstr+=chx;
}
}
// 计算后缀表达式的值
public static int doParse(String mystr){
char ch;
int num1,num2,result;
for(int i=0;i<mystr.length();i++){
ch=mystr.charAt(i);
if(ch>='0' && ch<='9')
stack1.push((int)(ch-'0'));
else{
num1=(int) stack1.pop();
num2=(int) stack1.pop();
switch(ch){
case '+':result=num1+num2;break;
case '-':result=num2-num1;break;
case '*':result=num1*num2;break;
case '/':result=num1/num2;break;
default:result=0;
}
stack1.push(result);
}
}
result=(int) stack1.pop();
return result;
}
}
/*
* 转为后缀表达式:
* (1)如果是(则直接入栈。。
* (2) 如果是)则将栈中的操作符依次加到输出中,直到遇到(
* (3)不是括号的情况下,如果不是操作符,则直接将它加到输出中,如果是操作符则要进行比较。如果该操作符的优先级高于栈顶的操作符,则直接
* 将该操作符入栈,否则的话将栈中的操作符依次取出加到输出中,直到遇到比该操作符优先级低的,并且将该操作符加入栈中,
* 如果扫描结束后栈中仍有操作符,则依次取出加到输出中。
*
*
*/
/*
* 后缀表达式计算
* 利用栈。。
* 只要遇到数字就入栈...
* 当遇到操作的符的时候就从栈中取出两个数字来进行计算。。并将计算后的值入栈。。。
* 最后剩下的则是计算的值。。。
*
*/
/*
* 这里只写的只适用于0-9.。。如果要适合多位数的数字,则只需简单的加个判断语句来讲多个数字当成一个数字。。
*
*/