首页 > 其他 > 详细

中缀表达式生成后缀表达式求解答案

时间:2019-09-18 21:58:25      阅读:114      评论:0      收藏:0      [点我收藏+]


import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;
import java.util.Stack;

class Solution
{


public static void main(String[] args){
Scanner sc=new Scanner(System.in);
String s=sc.nextLine();
System.out.println(getPost(s));
System.out.println(calc(getPost(s)));
}
public static int calc(List<Character> list){
Stack<String> stack=new Stack<String>();
for(char c:list){
if(c>=‘0‘&&c<=‘9‘){
stack.push(c+"");
}
if(c==‘+‘||c==‘-‘||c==‘*‘||c==‘/‘){
int b=Integer.parseInt(stack.pop());
int a=Integer.parseInt(stack.pop());
if(c==‘+‘){stack.push(a+b+"");}
if(c==‘-‘){stack.push(a-b+"");}
if(c==‘*‘){stack.push(a*b+"");}
if(c==‘/‘){stack.push(a/b+"");}
}
}
return Integer.parseInt(stack.pop());
}

public static List<Character> getPost(String s){
Stack<Character> stack=new Stack<Character>();
LinkedList<Character> list=new LinkedList<Character>();
for(int i=0;i<s.length();i++){
char c=s.charAt(i);
if(c<=‘9‘&&c>=‘0‘){
list.add(c);
}else if(c==‘+‘||c==‘-‘||c==‘*‘||c==‘/‘){

while(!stack.isEmpty())
{
if(compare(stack.peek())>=compare(c)){
list.add(stack.pop());

}else break;
}
stack.push(c);
}else if(c==‘(‘) stack.push(c);
else {
while(stack.peek()!=‘(‘){
list.add(stack.pop());
}
stack.pop();
}
}
while(!stack.isEmpty()){
list.add(stack.pop());
}
return list;
}
public static int compare(char c){
if(c==‘+‘||c==‘-‘) return 1;
else if(c==‘*‘||c==‘/‘) return 2;
else return 0;
}
}

 

技术分享图片

 

中缀表达式生成后缀表达式求解答案

原文:https://www.cnblogs.com/bestzj/p/11545423.html

(1)
(1)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!