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

 

 1 import java.util.LinkedList;
 2 import java.util.List;
 3 import java.util.Scanner;
 4 import java.util.Stack;
 5 
 6 class Solution
 7 {
 8 
 9 
10 public static void main(String[] args){
11 Scanner sc=new Scanner(System.in);
12 String s=sc.nextLine();
13 System.out.println(getPost(s));
14 System.out.println(calc(getPost(s)));
15 }
16 public static int calc(List<Character> list){
17 Stack<String> stack=new Stack<String>();
18 for(char c:list){
19 if(c>='0'&&c<='9'){
20 stack.push(c+"");
21 }
22 if(c=='+'||c=='-'||c=='*'||c=='/'){
23 int b=Integer.parseInt(stack.pop());
24 int a=Integer.parseInt(stack.pop());
25 if(c=='+'){stack.push(a+b+"");}
26 if(c=='-'){stack.push(a-b+"");}
27 if(c=='*'){stack.push(a*b+"");}
28 if(c=='/'){stack.push(a/b+"");}
29 }
30 }
31 return Integer.parseInt(stack.pop());
32 }
33 
34 public static List<Character> getPost(String s){
35 Stack<Character> stack=new Stack<Character>();
36 LinkedList<Character> list=new LinkedList<Character>();
37 for(int i=0;i<s.length();i++){
38 char c=s.charAt(i);
39 if(c<='9'&&c>='0'){
40 list.add(c);
41 }else if(c=='+'||c=='-'||c=='*'||c=='/'){
42 
43 while(!stack.isEmpty())
44 {
45 if(compare(stack.peek())>=compare(c)){
46 list.add(stack.pop());
47 
48 }else break;
49 }
50 stack.push(c);
51 }else if(c=='(') stack.push(c);
52 else {
53 while(stack.peek()!='('){
54 list.add(stack.pop());
55 }
56 stack.pop();
57 }
58 }
59 while(!stack.isEmpty()){
60 list.add(stack.pop());
61 }
62 return list;
63 }
64 public static int compare(char c){
65 if(c=='+'||c=='-') return 1;
66 else if(c=='*'||c=='/') return 2;
67 else return 0;
68 }
69 }

 

 

 

 

posted @ 2019-09-18 21:19  我爱黑科技77  阅读(161)  评论(0编辑  收藏  举报