import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
import java.util.Stack;
public class Main {
//将中缀表达式转为后缀表达式
public static void main(String[] args)throws IOException{
Scanner sc=new Scanner(new BufferedReader(new InputStreamReader(System.in)));
Stack<Character> stack=new Stack<Character>();//保存运算符的栈
stack.push('#');
String strmid=null;//保存中缀表达式
String strafter=null;//保存后缀表达式
System.out.println("请输入要转换的中缀表达式:");
strmid=sc.next();
for(int i=0;i<strmid.length();i++)
{
switch(strmid.charAt(i))
{
case ')':
while(stack.peek()!='(')
{
strafter=strafter+stack.pop();
}
stack.pop();//删除栈里的左括号
break;
case '#':
while(stack.peek()!='#')
{
strafter=strafter+stack.pop();
}
break;
case '+':
case '-':
case '*':
case '/':
case '(':
while(compare(strmid.charAt(i),stack.peek()))
{
strafter=strafter+stack.pop();
}
stack.push(strmid.charAt(i));
break;
default:
strafter=strafter+strmid.charAt(i);
break;
}
}
System.out.println("中缀表达式:"+strmid);
System.out.println("后缀表达式:"+strafter.replaceAll("null",""));
}
public static char infix_priority[]={'#',')','+','-','*','/','('};
public static char stack_priority[]={'#','(','+','-','*','/'};
public static boolean compare(char infix,char stack)
{ //比较运算符的优先级
int i=0,j=0;
while(infix_priority[i]!=infix)
{
i++;
}
while(stack_priority[j]!=stack)
{
j++;
}
boolean bool=(int)(j/2)>=(i/2)?true:false;
return bool;
}
}
java 实现中缀表达式转为后缀表达式
最新推荐文章于 2023-09-26 20:14:50 发布