zoukankan      html  css  js  c++  java
  • 逆波兰数Java实现

    定义^ 自增

    * 乘法

    + 加法

    栈长度16 超过 上溢出 返回-2  若栈中没有足够的整数供运算 则返回-1 否则返回栈顶

    package ali0426;
    
    import java.util.ArrayList;
    import java.util.List;
    import java.util.Scanner;
    import java.util.Stack;
    
    public class Main {
    
        public static void main(String[] args) {
    
            ArrayList<Integer> inputs = new ArrayList<Integer>();
            Scanner in = new Scanner(System.in);
            String line = in.nextLine();
            if(line != null && !line.isEmpty()) {
                int res = resolve(line.trim());
                System.out.println(String.valueOf(res));
            }
        }
    
        // write your code here
        public static int resolve(String expr) {
        	String str [] = expr.split(" ");
        	
        	
        	Stack<Integer> sta = new Stack<>();
        	int temp1,temp2;
        	//char [] ch = expr.toCharArray();
        	for(int i=0;i<str.length;i++){
        		String  c = str[i];
        		if(sta.size()>16) return -2;  //上溢出
        		if(c.equals("^")){
        			if(sta.size()==0) return -1;
        			else{
        				temp1 = sta.pop();
        				temp1++;
        				sta.push(temp1);
        			}
        				
        			
        		}
        		else if(c.equals("+")){
        			if(sta.size()<2) return -1;
        			else{
        				temp1 =sta.pop();
        				temp2 = sta.pop();
        				sta.push(temp1+temp2);
        			}
        			
        		}
        		else if(c.equals("*")){
        			if(sta.size()<2) return -1;
        			else{
        				temp1 =sta.pop();
        				temp2 =sta.pop();
        				sta.push(temp1*temp2);
        		        
        			}
        			
        		}
        		else if(c.equals(" ")) continue;//处理空格
        		else{
        			sta.add(Integer.parseInt(c));
        		}
        		
        	}
    		return sta.peek();
    
            
           
        }
    }
    

      

  • 相关阅读:
    财务自由之路
    权力的48条法则
    将进酒
    DELL服务器报价,有公司需要可以联系,谢谢。北京经纬恒通商贸有限公司秦嘉俊
    实战HTML5表单
    《HTML5+CSS3精通》
    行路难
    事件入门
    DOM
    剑指offer---包含min函数的栈
  • 原文地址:https://www.cnblogs.com/CongLollipop/p/6771125.html
Copyright © 2011-2022 走看看