逆波兰法(计算器)程序<无括号版>
涉及队列、栈的运用。
Java中队列可以用:
Queue<String> q = new LinkedList();
来声明,其主要的方法有:
poll(),peak(),offer(),clear(),size()等。
Java中栈可以用:
Stack s = new Stack();
来声明,其主要方法有:
push(),peak(),pop(),clear(),size()等。
1 package preTest; 2 3 import java.util.LinkedList; 4 import java.util.Queue; 5 import java.util.Scanner; 6 import java.util.Stack; 7 8 //逆波兰表示法 9 public class nbl { 10 public static Stack sigStack = new Stack(); 11 public static Queue<String> nblQueue = new LinkedList(); 12 public static Stack numFromQueue = new Stack(); 13 public static void main(String[] args) { 14 Scanner in=new Scanner(System.in); 15 while(in.hasNext()){ 16 String str = in.nextLine(); 17 int result = cal(str); 18 System.out.println(result); 19 } 20 } 21 22 public static int cal(String str){ 23 sigStack.clear(); 24 nblQueue.clear(); 25 StringBuilder sb = new StringBuilder(); 26 int len = str.length(); 27 int result= 0; 28 //压栈和入队操作 29 for(int i=0; i<len;i++){ 30 char c = str.charAt(i); 31 if(c>='0' && c <='9'){ 32 sb.append(c); 33 if(i==len-1){ 34 nblQueue.offer(sb.toString()); 35 } 36 }else{ 37 nblQueue.offer(sb.toString()); 38 sb.replace(0, sb.length(), ""); 39 if(sigStack.size() == 0){ 40 sigStack.push(c); 41 }else{ 42 char existed = (char)sigStack.peek(); 43 //如果已经压栈的符号优先级>=当前符号c,则完成压栈符号的操作 44 if(c=='+' || c=='-'){ 45 zhengli(); 46 sigStack.push(c); 47 //当两个都是乘除运算时 48 }else if(existed =='*' || existed == '/'){ 49 tinyAdjust(c); 50 }else{//新符号乘除,旧符号加减 51 sigStack.push(c); 52 } 53 } 54 } 55 } 56 zhengli(); 57 //出队操作 58 numFromQueue.clear(); 59 result = releaseQueue(); 60 return result; 61 } 62 63 public static void zhengli(){ 64 while(sigStack.size() > 0){ 65 char c = (char)sigStack.pop(); 66 nblQueue.offer(new StringBuilder().append(c).toString()); 67 } 68 } 69 70 public static void tinyAdjust(char c){ 71 char ch = (char)sigStack.pop(); 72 nblQueue.offer(new StringBuilder().append(ch).toString()); 73 sigStack.push(c); 74 } 75 76 public static int releaseQueue(){ 77 int len = nblQueue.size(); 78 boolean isNum = false; 79 for(int i=0; i<len; i++){ 80 isNum = judge(); 81 if(isNum){ 82 int num = Integer.parseInt(nblQueue.poll()); 83 numFromQueue.push(num); 84 }else{ 85 int a = (int)numFromQueue.pop(); 86 int b = (int)numFromQueue.pop(); 87 char c = nblQueue.poll().charAt(0); 88 int res = compute(b,a,c); 89 numFromQueue.push(res); 90 } 91 } 92 return (int)numFromQueue.pop(); 93 } 94 95 public static boolean judge(){ 96 String str = nblQueue.peek(); 97 char c = str.charAt(0); 98 if(c>='0' && c<='9'){ 99 return true; 100 }else{ 101 return false; 102 } 103 } 104 105 //简单加减乘除计算 106 public static int compute(int a, int b, char c){ 107 int result = 0; 108 switch(c){ 109 case '+': result = a+b; 110 break; 111 case '-': result = a-b; 112 break; 113 case '*': result = a*b; 114 break; 115 case '/': result = a/b; 116 break; 117 } 118 return result; 119 } 120 121 }