逆波兰表达式

来源:互联网 发布:数据可视化软件下载 编辑:程序博客网 时间:2024/05/16 17:06

基本栈的操作



import java.util.*;public class TestStack {  public static void main(String args[])  { Stack <String>st = new Stack<String> ();    //定义一个栈 String Str; Scanner input = new Scanner(System.in);Str=input.nextLine();String[] inputss = Str.split(" ");for(String ch:inputss){switch(ch){case "*":if (st.size()<2){System.out.println("-1");break;}else {st.push(String.valueOf((Integer.valueOf(st.pop())*Integer.valueOf(st.pop()))));}case "+": if(st.size()<2){System.out.println("-1");break;}else {st.push(String.valueOf((Integer.valueOf(st.pop())+Integer.valueOf(st.pop()))));}case "^":if(st.size()<1){System.out.println("-1");break;}else {st.push(String.valueOf(Integer.valueOf(st.pop())+1));}default:if(st.size()>16)System.out.println("-2");else st.push(ch);break;}  //swich}   //forSystem.out.println(st.pop());    }}

本例运行结果:98

0 0